10 Examples to Master Python Dictionary Comprehensions | by Soner Yıldırım | Towards Data Science

A dictionary is an unordered collection of key-value pairs. Each entry has a key and value. A dictionary can be considered as a list with special index.
The keys must be unique and immutable. So we can use strings, numbers (int or float), or tuples as keys. Values can be of any type.
In this article, we will focus on dictionary comprehension which is a method to create dictionaries using iterables. The logic is the same as list comprehension but the syntax is different due to the structure of dictionaries.
In order to see the similarity between a list and dictionary comprehension, I will create both a list and dictionary comprehension in the first two examples.
words = ['data', 'science', 'machine', 'learning']#list comprehension[len(i) for i in words][4, 7, 7, 8]#dictionary comprehension{i:len(i) for i in words}{'data': 4, 'science': 7, 'machine': 7, 'learning': 8}
We have an iterable which is a list named “words”. In the list comprehension, we create a list that contains the length of the words. In the dictionary comprehension, we need to specify both keys and values based on the iteration. The returned dictionary contains the words as keys and their length as values.
The basic syntax for list and dictionary comprehension are:
For this example, we will repeat the task in the first example with an additional condition. Both list and dictionary comprehensions accept if/else conditional statements.
words = ['data', 'science', 'machine', 'learning']#list comprehension[len(i) for i in words if len(i) > 5][7, 7, 8]#dictionary comprehension{i:len(i) for i in words if len(i) > 5}{'science': 7, 'machine': 7, 'learning': 8}
The returned variables only contain the words longer than 5 characters.
In this example, we will slightly increase the complexity of the conditional statement.
words_dict = {i:len(i) if len(i) > 5 else 'short' for i in words}print(words_dict){'data': 'short', 'science': 7, 'machine': 7, 'learning': 8}
We implement an if/else conditional in the dictionary comprehension. If the length is greater than 5, the value becomes the length. Otherwise, we assign the word ‘short’ as the value.
What makes comprehensions appealing is their one liner syntax. It looks quite simple and easier to understand than the equivalent for loops. For instance, the equivalent for loop of the comprehension above is:
We can iterate over two iterables in a dictionary comprehension.
words = ['data', 'science', 'machine', 'learning']values = [5, 3, 1, 8]dict_a = {i:j for i, j in zip(words, values)}print(dict_a){'data': 5, 'science': 3, 'machine': 1, 'learning': 8}
Key-value pairs are created by iterating over separate lists for keys and values. The zip function returns an iterable of tuples by combining the items from each list.
We can also put a condition on the values when iterating over a list of tuples.
words = ['data', 'science', 'machine', 'learning']values = [5, 3, 1, 8]dict_a = {i:j for i, j in zip(words, values) if j > 4}print(dict_a){'data': 5, 'learning': 8}
We can also apply transformations on key-value pairs.
dict_b = {i.upper():j**2 for i, j in zip(words, values)}print(dict_b){'DATA': 25, 'SCIENCE': 9, 'MACHINE': 1, 'LEARNING': 64}
Both keys and values are modified using simple Python methods.
We can access the key-value pairs in a dictionary by using the items method.
print(dict_b.items())dict_items([('DATA', 25), ('SCIENCE', 9), ('MACHINE', 1), ('LEARNING', 64)])
We can use the items of an existing dictionary as iterable in a dictionary comprehension. It allows us to create dictionaries based on existing dictionaries and modify both keys and values.
dict_c = {i.lower():j%2 for i, j in dict_b.items()}print(dict_c){'data': 1, 'science': 1, 'machine': 1, 'learning': 0}
The enumerate function of Python can be used to create an iterable of tuples based on a list. Each tuple contains the items in the list with incrementing integer values.
names = ['John', 'Jane', 'Adam', 'Eva', 'Ashley']list(enumerate(names))[(0, 'John'), (1, 'Jane'), (2, 'Adam'), (3, 'Eva'), (4, 'Ashley')]
We can use the enumerate function in a dictionary comprehension.
dict_names = {i:len(j) for i, j in enumerate(names)}print(dict_names){0: 4, 1: 4, 2: 4, 3: 3, 4: 6}
If you just want to create a dictionary based on a list of tuples without any modification on the values, you do not need to use a comprehension. The dict function will do the job.
dict(enumerate(names)){0: 'John', 1: 'Jane', 2: 'Adam', 3: 'Eva', 4: 'Ashley'}
This example contains a slightly more complicated conditionals than the previous ones. Consider we have the following dictionary and list.
lst = ['data','science','artificial', 'intelligence']dct = {'data': 5, 'science': 3, 'machine': 1, 'learning': 8}
We want to create a new dictionary using the list and dictionary defined above. The keys of the new dictionary will be the elements in the list so we will iterate over the elements in list. If the element is also in the dictionary, the value will be the values of that key in the dictionary. Otherwise, the value will be the length of the key.
{i:dct[i] if i in dct else len(i) for i in lst}{'artificial': 10, 'data': 5, 'intelligence': 12, 'science': 3}
The word artificial is not in the dictionary so its value is the length of the word. The word data is in the dictionary so its value is taken from the dictionary.
The keys of a dictionary must be immutable so tuples can be used as keys. Dictionary comprehensions allow for generating keys of tuples by implemented nested loops.
a = [1,2,3,4]b = [5,6,7]dct = {(i,j):i*j for i in a for j in b}print(dct){(1, 5): 5, (1, 6): 6, (1, 7): 7, (2, 5): 10, (2, 6): 12, (2, 7): 14, (3, 5): 15, (3, 6): 18, (3, 7): 21, (4, 5): 20, (4, 6): 24, (4, 7): 28}
Each pair of items in the lists is a key in the dictionary. The value is the product of the items in keys.
The equivalent for loop syntax:
Dictionaries are very important data structures in Python and used in many cases. The examples we did in this post will cover most of what you need to know about dictionary comprehensions. They will make you feel comfortable when working with and creating new dictionaries.
Thank you for reading. Please let me know if you have any feedback.