Dictionary Generation with Dictionary Comprehension in Python
To create a dictionary, you can also use a comprehension. Its syntax will look like this:
dictionary = { key: value for element in iter }
Let's create a dictionary where the key
is generated in the range from 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}
Given two lists:
lst1 = ['name1', 'name2', 'name3', 'name4']
lst2 = ['john', 'kate', 'alex', 'mary']
Using them, create a dictionary where the keys are the elements of the first list, and the values are from the second list:
{'name1': 'john', 'name2': 'kate', 'name3': 'alex', 'name4': 'mary'}