Close
Close

Python Dictionary Comprehension


Like list comprehension, we can use dictionary comprehension for creating dictionaries which are otherwise created using a for loop. Dictionary comprehension makes creating dictionaries easier and more readable.

So, let’s see how to create dictionaries using dictionary comprehension.

Using Dictionary Comprehension


Let’s take an example which stores the cube of all numbers from 1 to 10 in a dictionary using a for loop.

cubes = {}

for num in range(1, 11):
    cubes[num] = num**3

print(cubes)
Output
{1: 1, 2: 8, 3: 27, 4: 64, 5: 125, 6: 216, 7: 343, 8: 512, 9: 729, 10: 1000}

In the dictionary cubes, the keys are the numbers from 1 to 10 and the values are the cubes of the corresponding keys.

We created an empty dictionary cubes. Then we iterate over range(1, 11) using a for loop. In each iteration, the key is assigned the number and the cube of the number is calculated and the result is assigned to the value.

The dictionary cubes can be created using dictionary comprehension as follows.

cubes = {num: num**3 for num in range(1, 11)}
print(cubes)
Output
{1: 1, 2: 8, 3: 27, 4: 64, 5: 125, 6: 216, 7: 343, 8: 512, 9: 729, 10: 1000}

On looking at [num: num**3 for num in range(1, 11)], you will find a for loop definition - for num in range(1, 11).

In for num in range(1, 11), the variable num iterates over range(1, 11). 

In each iteration, an element with the key equal to num and the value equal to the num**3 is added to a dictionary and that dictionary is returned at the end of the loop. 

In the first iteration, num is 1. Thus, the key is 1 and the value is also 1 (1**3 = 1).

In the second iteration, num is 2. Thus, the key is 2 and the value is also 8 (2**3 = 8).

This goes on till all the ten iterations. Finally, the dictionary created is assigned to the variable cubes.

So we have just created a dictionary using dictionary comprehension. Now let’s look at the general syntax of dictionary comprehension.

Python Dictionary Comprehension Syntax


new_dictionary = {key: value for_loop}

The dictionary returned by dictionary comprehension method is enclosed within braces { }. On each iteration of the for_loop, an element is added to the dictionary with key as the key and value as the value.

Comparing this syntax to the last example, num is key, num**3 is value and for num in range(1, 11) is for_loop.

dictionary comprehension syntax

Python Dictionary Comprehension Examples


Let’s look at an example in which we will create a dictionary from the elements of another dictionary.

fruits = {'mango': 40, 'banana': 10, 'cherry': 20}
new_fruits = {}

for fruit, price in fruits.items():
    new_fruits[fruit] = price * 2
	
print(new_fruits)
Output
{'mango': 80, 'banana': 20, 'cherry': 40}

We have a dictionary fruits storing three fruits and their prices. We are creating another dictionary new_fruits storing the same fruits with double their prices. For that, we iterate through the items of the fruits dictionary using items() and append a new item to the new_fruits dictionary in each iteration.

The dictionary new_fruits can be created using dictionary comprehension as follows.

fruits = {'mango': 40, 'banana': 10, 'cherry': 20}
new_fruits = {fruit: price*2 for (fruit, price) in fruits.items()}
print(new_fruits)
Output
{'mango': 80, 'banana': 20, 'cherry': 40}

In the above program, in each iteration  of the loop for (fruit, price) in fruits.items(), an element with key as fruit and value as price*2 is added to a dictionary and that dictionary is retired at the end of the loop.

Comparing this code to the syntax, fruit is key, price*2 is value and for (fruit, price) in fruits.items() is for_loop.

Using Dictionary Comprehension with Conditional Statements


Let’s see how to implement dictionary comprehension when an if statement is used in the body of for loop.

Syntax

new_dictionary = {key: value for_loop if condition}

On each iteration of the for_loop, the if condition is checked. If the condition is True, then only the element is added to the dictionary.

Examples

Suppose in the last example, we want to create a new dictionary new_fruits only for those fruits whose price is greater than 15. This is done using a for loop in the following example.

fruits = {'mango': 40, 'banana': 10, 'cherry': 20}
new_fruits = {}

for fruit, price in fruits.items():
    if price > 15:
        new_fruits[fruit] = price * 2
Output
{'mango': 80, 'cherry': 40}

Let’s create this dictionary using dictionary comprehension.

fruits = {'mango': 40, 'banana': 10, 'cherry': 20}
new_fruits = {fruit: price*2 for (fruit, price) in fruits.items() if price > 15}
print(new_fruits)
Output
{'mango': 80, 'cherry': 40}

Comparing this code to the syntax, fruit is key, price*2 is value, for (fruit, price) in fruits.items() is for_loop and if price > 15 is if condition.

Python if...else With Dictionary Comprehension


Like in list comprehension, using if...else in dictionary comprehension has a slightly different syntax than using just if. Let’s look at the two syntaxes.

Syntax of Dictionary Comprehension including if statement

new_list = {key: value for_loop if condition}

We have already seen examples where if statements were used.

Syntax of Dictionary Comprehension including if..else statement

new_list = {key: (value1 if condition else value2) for_loop}

Here, if the condition of if is True, then value1 is evaluated and assigned to key, else value2 is evaluated and assigned to key. Rest everything is the same.

Let’s see how if..else is implemented in dictionary comprehension.

Take an example in which we have a dictionary containing the names of students along with their marks. The names are the keys and the marks are the values. We have to create another dictionary with the names as the keys and ‘Pass’ or ‘Fail’ as the values depending on whether the student passed or failed, assuming the passing marks are 40.

result = {"John": 45, "Mark": 70, "Jack": 32, "Devin": 65}
new_result = {}

for name, marks in result.items():
    if marks >= 40:
        new_result[name] = "Pass"
   &nbspelse:
        new_result[name] = "Fail"

print(new_result)
Output
{'John': 'Pass', 'Mark': 'Pass', 'Jack': 'Fail', 'Devin': 'Pass'}

We iterate through the items of the result dictionary using items(). In each iteration, we check if the value (marks) is greater than or equal to 40. If it is, then we append a new element to the new dictionary new_result with the same key and the value "Pass", otherwise we append the element with the value "Fail".

This can be created using dictionary comprehension as follows.

result = {"John": 45, "Mark": 70, "Jack": 32, "Devin": 65}
new_result = {name: ("Pass" if marks >= 40 else "Fail") for (name, marks) in result.items()}
print(new_result)
Output
{'John': 'Pass', 'Mark': 'Pass', 'Jack': 'Fail', 'Devin': 'Pass'}

name is key, "Pass" is value1, "Fail" is value2, marks >= 40 is condition and for (name, marks) in result.items() is for_loop. In each iteration of for_loop, if condition is True, then value1 is assigned to the key, else value2 is assigned to the key.

When to use Dictionary Comprehension


Dictionary comprehension makes creating dictionaries faster and more readable. However, it should not be used every time to create a dictionary. If the logic is long or complex, then using dictionary comprehension is a bad choice. This is because it can become less readable and you won’t be able add comments, thus making it difficult to debug as well.

Therefore, use dictionary comprehension if the logic is simple and small and use for loop otherwise.

To learn from simple videos, you can always look at our Python video course on CodesDope Pro. It has over 500 practice questions and over 20 projects.
Wisely, and slow. They stumble that run fast.
- William Shakespeare


Ask Yours
Recent Posts
asds
asds
jasd
jasd
as
as
Post Yours
Doubt? Ask question