List Comprehension is a handy and faster way to create lists in Python in just a single line of code. It helps us write easy to read for loops in a single line.
In Python, dictionary is a data structure to store data such that each element of the stored data is associated with a key. Dictionary data structure lets you query the data using key very efficiently.
The idea of comprehension is not just unique to lists in Python. Dictionaries, one of the commonly used data structures in data science, can also do comprehension. With dict comprehension or dictionary comprehension, one can easily create dictionaries.
Remember that, in python a list is defined with square brackets [] and a dictionary is defined with curly braces {}. The idea used in list comprehension is carried over in defining dict comprehension as well. Dict comprehension is defined with a similar syntax, but with a key:value pair in expression.
- {key:value for i in list}
Let us see 5 simple examples of using Dict Comprehension to create new dictionaries easily.
[update:] Added sixth example of dict comprehension to delete keys in a dictionary.
Dict Comprehension Example 1
Let us see a quick example of creating a dict comprehension from a list of numbers.
Here let us use a list of numbers and create a dictionary with string value of the number as key and the number as values.
# dict comprehension to create dict with numbers as values >{str(i):i for i in [1,2,3,4,5]} {'1': 1, '3': 3, '2': 2, '5': 5, '4': 4}
Dict Comprehension Example 2
Let us say, we have a list of fruits and we can use dict comprehension to create a dictionary with fruits, the list elements as the keys and the length of each string as the values.
# create list of fruits >fruits = ['apple', 'mango', 'banana','cherry'] # dict comprehension to create dict with fruit name as keys >{f:len(f) for f in fruits} {'cherry': 6, 'mango': 5, 'apple': 5, 'banana': 6}
Dict Comprehension Example 3
Let us create a dictionary with dict comprehension such that elements of the list as the keys and the elements with first letter capitalized as the values.
>{f:f.capitalize() for f in fruits} {'cherry': 'Cherry', 'mango': 'Mango', 'apple': 'Apple', 'banana': 'Banana'}
Dict Comprehension Example 4
Let us use enumerate function in dictionary comprehension. If you have not used enumerate: enumerate can take any thing iterable as input and returns element and its index.
Here we use enumerate function on the list to create index and list element tuples and use them to create a dictionary with dict comprehension. We create a dictionary with elements of the list as the keys and the index of elements as the values. Such dictionaries with element index are often useful in a variety of scenarios.
# dict comprehension example using enumerate function >{f:i for i,f in enumerate(fruits)} {'cherry': 3, 'mango': 1, 'apple': 0, 'banana': 2}
Dict Comprehension Example 5
Another use of dict comprehension is to reverse key:value in an existing dictionary. Sometimes you may want to create new dictionary from an existing directory, such that the role of key:value pair in the first dictionary is reversed in the new dictionary. We can use Dict Comprehension and flip the element to index dictionary to index to element dictionary.
# dict comprehension example to reverse key:value pair in a dictionary >f_dict = {f:i for i,f in enumerate(fruits)} >f_dict {'apple': 0, 'banana': 2, 'cherry': 3, 'mango': 1} # dict comprehension to reverse key:value pair in a dictionary >{v:k for k,v in f_dict.items()} {0: 'apple', 1: 'mango', 2: 'banana', 3: 'cherry'}
We have used dictionaries’ items function to get key, value pairs in an existing dictionary and created a new dictionary where the keys in the original dictionary are values in new dictionary and vice versa.
Dict Comprehension Example 6: How To Delete Selected Keys from Dictionary using Dict Comprehension?
Let us say you have dictionary and want to create a new dictionary by removing certain key-value pair. We can use Dict Comprehension to remove selected key-value pairs from a dictionary and create a new dictionary.
Let us use the “fruit” dictionary we created above.
fruits = ['apple', 'mango', 'banana','cherry'] f_d1 ={f:f.capitalize() for f in fruits} f_d1
Let us use diction comprehension to remove two keys, apple and banana, and their values from the fruit dictionary.
# keys to be removed >remove_this = {'apple','cherry'} # dict comprehension example to delete key:value pairs in a dictionary >{key:f_d1[key] for key in f_d1.keys() - remove_this} {'banana': 'Banana', 'mango': 'Mango'}
We have removed the keys, apple and cherry, by simply using dict keys object with set operations and now the new dictionary contains just banana and mango.