English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python Basic Tutorial

Python Flow Control

Python Functions

Python Data Types

Python File Operations

Python Objects and Classes

Python Date and Time

Advanced Python Knowledge

Python Reference Manual

Python Dictionary Comprehension

In this tutorial, we will learn about Python dictionary comprehension and how to use it with the help of examples.

Dictionaries are a data type in Python that allows us to store data inKey/In the value pair. For example:

my_dict = {1: 'apple', 2: 'ball'

For more information about them, please visit:Python dictionary

What is dictionary comprehension in Python?

Dictionary comprehension is an elegant and concise way to create dictionaries.

Example1: Dictionary comprehension

Consider the following code:

square_dict = dict()
for num in range(1, 11) :
    square_dict[num] = num*num
print(square_dict)

Now, let's use the dictionary comprehension function to create a dictionary in the above program.

# Dictionary comprehension example
square_dict = {num: num*num for num in range(1, 11)}
print(square_dict)

The output of the two programs will be the same.

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}

In these two programs, we both created square_dict withnumeric square keys/value pairsof our dictionary.

However, using dictionary comprehension can make usin one lineCreateDictionary.

Using dictionary comprehension

From the above examples, we can see that dictionary comprehension should be written in a specific pattern.

The minimum syntax for dictionary comprehension is:

dictionary = {key: value for vars in iterable}

Let's compare this syntax with the dictionary comprehension in the previous example.

Now, let's see how to use dictionary comprehension with data from another dictionary.

Example3:How to use dictionary comprehension

#item price in dollars
old_price = {'milk': 1.02, 'coffee': 2.5, 'bread': 2.5}
dollar_to_pound = 0.76
new_price = {item: value*dollar_to_pound for (item, value) in old_price.items()}
print(new_price)

Output Result

{'milk': 0.7752, 'coffee': 1.9, 'bread': 1.9}

Here, we can see that we retrieve the price of goods in dollars and convert it to pounds. Using dictionary comprehension makes this task simpler and shorter.

Condition in dictionary comprehension

We can further customize dictionary comprehension by adding conditions. Let's look at an example.

Example4:if condition dictionary comprehension

original_dict = {'jack': 38, 'michael': 48, 'guido': 57, 'john': 33}
even_dict = {k: v for (k, v) in original_dict.items() if v % 2 == 0}
print(even_dict)

Output Result

{'jack': 38, 'michael': 48}

We can see that due to the clauses in the if dictionary comprehension, only items with even values are added.

Example5:multiple if condition dictionary comprehension

original_dict = {'jack': 38, 'michael': 48, 'guido': 57, 'john': 33}
new_dict = {k: v for (k, v) in original_dict.items() if v % 2 != 0 if v < 40}
print(new_dict)

Output Result

{'john': 33}

In this case, only odd values less than40 items have been added to the new dictionary.

This is because there are multiple clauses in the if dictionary comprehension. They are equivalent to and, and both conditions must be met simultaneously.

Example6:if-else condition dictionary comprehension

original_dict = {'jack': 38, 'michael': 48, 'guido': 57, 'john': 33}
new_dict_1 = {k: ('old' if v > 40 else 'young'
    for (k, v) in original_dict.items()}
print(new_dict_1)

Output Result

{'jack': 'young', 'michael': 'old', 'guido': 'old', 'john': 'young'}

In this case, a new dictionary will be created through sub-dictionary comprehension.

Value greater than or equal to4The value of the item '0' is 'old', and the value of other items is 'young'.

Nested Dictionary Comprehension

We can add dictionary comprehension itself to dictionary comprehension to create nested dictionaries. Let's look at an example.

Example7: Nested dictionary with two dictionary comprehensions

dictionary = {
    k1: {k2: k1 * k2 for k2 in range(1, 6)} for k1 in range(2, 5)
}
print(dictionary)

Output Result

{2: {1: 2, 2: 4, 3: 6, 4: 8, 5: 10}, 
3: {1: 3, 2: 6, 3: 9, 4: 12, 5: 15},
4: {1: 4, 2: 8, 3: 12, 4: 16, 5: 20}}

As you can see, we have constructed a multiplication table in the nested dictionary for2to4numbers.

When using nested dictionary comprehensions, Python will start from the outer loop first, and then enter the inner loop.

Therefore, the above code is equivalent to:

dictionary = dict()
for k1 in range(11, 16) :
    dictionary[k1]= {k2: k1*k2 for k2 in range(1, 6)}
print(dictionary)

It can be expanded further:

dictionary = dict()
for k1 in range(11, 16) :
    dictionary[k1] = dict()
    for k2 in range(1, 6) :
        dictionary[k1][k2] = k1*k2
print(dictionary)

These three programs give us the same output.

Advantages of using dictionary comprehensions

As we have seen, dictionary comprehensions greatly shorten the process of dictionary initialization. It makes the code more pythonic.

Using dictionary comprehensions in our code can shorten the code lines while maintaining the integrity of the logic.

Considerations when using dictionary comprehensions

Although dictionary comprehensions are very useful for writing easy-to-read elegant code, they are not always the correct choice.

Use them as:

  • They may sometimes slow down the code execution speed and consume more memory.

  • They will also reduce the readability of the code.

We must never try to add difficult logic or a large number of dictionary comprehensions just to make the code single-line. In these cases, it is best to choose other alternative methods, such as loops.