Skip to content
Search
Generic filters
Exact matches only

7 Handy Use Cases Of Dictionary Comprehensions In Python

Consider the following code that creates a dictionary from a range of numbers with the value being the square of the key:

square_dict = {num: num*num for num in range(1, 6)}
print(square_dict)
#Output
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Now let’s analyze the syntax of the dictionary expression using the above code as a reference:

The above syntax represents the minimal form of writing a dictionary comprehension. The output of the dictionary comprehension is highlighted in green. All the key-value pairs are assigned to the constructed dictionary.

The iterable doesn’t have to be a dictionary. It can be any python object on which you can loop over — list, tuple, strings, etc.

Unlike list comprehensions, a dictionary comprehension can iterate over a group of keys and values simultaneously as well. By invoking the method on a dictionary, you can convert it into a list of tuples of key-value to loop over.

You can also set a conditional statement after the loop in dictionary comprehension as shown below:

fruits = ['Apple', 'Orange', 'Papaya', 'Banana', '']fruits_dict = {f:len(f) for f in fruits if len(f) > 0}print(fruits_dict)
#Output
{'Apple': 5, 'Orange': 6, 'Papaya': 6, 'Banana': 6}

Now that we’ve got a good look at the syntax of dictionary comprehensions, let’s move onto its applications.