Python Dictionary Comprehension


Python dictionary data type is used to store data in key:value pairs. It can be created in two ways first is by placing the comma-separated items inside curly braces and the second is to create using dict() function.

For example –

users={1:'Ankit', 2:'Sumit', 3:'John', 4:'Vinay'}

Python dictionary comprehension provides a shorter syntax to create dictionaries. In this article, you will learn Python dictionary comprehension and how to use it.

How to create a dictionary using dictionary comprehension

The syntax for creating a Python dictionary using dictionary comprehension is given below.

dict_var={key:value for (key, value) in iterable}

Where dict_var is the dictionary variable, the key: value pairs will get added to dict_var.

Example of Python dictionary created using dictionary comprehension

In our example, we will create a dictionary whose keys range from 0 to 5  and whose values are the cube of corresponding keys. First, we will create this with the usual method that we use later we create using dictionary comprehension.

cube_dict = dict()
for num in range(0,6):
     cube_dict[num] = num**3
print(cube_dict)

How to Use dictionary comprehension in Python

You can write the same code in a few lines by using dictionary comprehension. Now see the code below.

cube_dict = {num:num**3 for num in range(0,6)}
print(cube_dict)

You can see the output in the given image –

how to use python dictionary comprehension

Use of Python conditional statements in dictionary comprehension

You can use any python conditional statements in dictionary comprehension to modify the output on the basis of a condition. We will understand this with the help of an example.

We will create a dictionary with keys even numbers ranging from 1 to 15 and whose values are cubes of corresponding keys.

cube_dict = {num: num**3 for num in range(1,15) if num%2==0}
print(cube_dict)

You can see the output of this in the given image –

conditional statement in python dictionary comprehension

Python nested dictionary

A dictionary inside a dictionary is known as a nested dictionary. An example of a nested dictionary is given below-

users={ 1:{'name':'Sumit', 'age'=24},
        2:{'name':'Ajay' 'age'=25},
        3:{'name':'Vinay' 'age'=20}
      }

The syntax for creating Python nested dictionary using dictionary comprehension is given below:

dict_var={outer_k:{inner_k:inner_v for inner_k,inner_v in outer_v.items()} for outer_k, outer_v in outer_dict.items()}

Where inner_k and inner_v are the key and value of the inner dictionary similarly outer_k and outer_v are the key and value of the outer dictionary.

Conclusion

Python dictionary comprehension provides a shorter syntax to create dictionaries so you can write the same code in fewer lines.

Now you can leave your query in the comments below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.