⊗pyPmCoDi 32 of 128 menu

Generating a Dictionary Using Dictionary Inclusion in Python

You can also use inclusion to create a dictionary. The syntax will look like this:

dictionary = { key: value for element in iter }

Let's make a dictionary where the key will be generated in the range 1 to 4. And the value will be the square of the key:

dct = {i: i ** 2 for i in range(1, 5)} print(dct)

After executing the code, the following dictionary will be returned:

{1: 1, 2: 4, 3: 9, 4: 16}

Given a list:

lst = ['a', 'b', 'c', 'd', 'e']

Using this list, create a dictionary where the keys are the elements of our list and the values ​​are their ordinal numbers:

{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

Two lists are given:

lst1 = ['name1', 'name2', 'name3', 'name4'] lst2 = ['john', 'kate', 'alex', 'mary']

Using them, create a dictionary in which the keys will be the elements of the first list, and the values ​​will be the elements of the second list:

{'name1': 'john', 'name2': 'kate', 'name3': 'alex', 'name4': 'mary'}
enru