5 Examples Using Dict Comprehension in Python

List Comprehension is really a handy and faster way to write for loops in Python in just a single line of code. 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. This is called dict comprehension or dictionary comprehension.

Remember that, in python a list is defined with square brackets [] and a dictionary is defined with curly braces {}. The same idea 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}

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.

>{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

We have a list of fruits and we can use dict comprehension to create a dictionary with list elements as the keys and the length of each string as the values.

>fruits = ['apple', 'mango', 'banana','cherry']
>{f:len(f) for f in fruits}
{'cherry': 6, 'mango': 5, 'apple': 5, 'banana': 6}

Dict Comprehension Example 3

Here we are creating a dictionary with dict comprehension such that elements of the list elements 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

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 such that 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.

>{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. Here we flip the element to index dictionary to index to element dictionary.

>f_dict = {f:i for i,f in enumerate(fruits)}
>{v:k for k,v in f_dict.items()}
{0: 'apple', 1: 'mango', 2: 'banana', 3: 'cherry'}