In this tutorial, we are going to learn how to use dictionary comprehensions in Python. If you are already familiar with list comprehension, then it won't take much time to learn dictionary comprehensions.
We need the key: value pairs to create a dictionary. How to get these key-value pairs using dictionary comprehension? See the general statement of dictionary comprehension.
{key: value for ___ in iterable}
We need to fill in the above statement to complete a dictionary comprehension. There are many ways to fill it. Let's see some of the most common ways.
Let's see how to generate numbers as keys and their squares as values within the range of 10. Our result should look like {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}. See the code below.
Example
# creating the dictionary squares = {i: i ** 2 for i in range(10)} # printing the dictionary print(squares)
Output
If you run the above code, you will get the following result.
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
How to create a dictionary from two lists using this comprehension? We can use the zip method to get parallel values from two lists. Let's see how to create a dictionary from [1, 2, 3, 4, 5] and [a, b, c, d, e].
Example
# keys keys = ['a', 'b', 'c', 'd', 'e'] # values values = [1, 2, 3, 4, 5] # creating a dict from the above lists dictionary = {key: value for (key, value) in zip(keys, values)} # printing the dictionary print(dictionary)
Output
If you execute the above program, you will get the following output.
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
We can also generate a dictionary from a single list with index as key using the enumerate method. Let's see how to do it.
Example
# values values = ['a', 'b', 'c', 'd', 'e'] # generating a dict using enumerate dictionary = {key: value for (key, value) in enumerate(values)} # printing the dict print(dictionary)
Output
If you run the above code, then you will get the following output.
{0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e'}
Conclusion
You can use the dictionary comprehensions based on your need. The best way to learn master dictionary comprehensions is to use them whenever there is a possibility. If you have any doubts in the tutorial, mention them in the comment section.