Dictionary Comprehension in Python

  • Dictionary comprehension are just like list comprehensions
  • It is an elegant and concise way to create dictionaries.

Dictionary Comprehension Advantages

  • Using dictionary comprehension in our code can shorten the lines of code while keeping the logic intact.

Dictionary Comprehension Disadvantages

  • It can sometimes make the code run slower and consume more memory.
  • It can also decrease the readability of the code.

Please read the previous topic for more understanding about Python
List in Python
Tuple in Python
Sets in Python
Dictionary in Python

Question – Create a dictionary for the cube of the number 10.

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

O/P –

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

O/P –

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

Using dictionary comprehension allowed us to create a dictionary in a single line.
We can see that comprehension should be written in a specific pattern.
The minimal syntax for dictionary comprehension is:

dictionary = {key: value for vars in iterable}

Question – Create a new dictionary with only pairs where the key is larger than 100.

d = {104: "Naresh", 89 : "Rio", 432: "Vikash", 23 : "Ethan"}

new_dict = {k:v for k,v in d.items() if k >100}
print(new_dict)

O/P –

{104: 'Naresh', 432: 'Vikash'}

We can also use with a nested dictionary. Please see the below example.

dictionary = dict()
for k1 in range(20, 23):
    dictionary[k1] = {k2: k1*k2 for k2 in range(1, 3)}
print(dictionary)

O/P –

{20: {1: 20, 2: 40}, 21: {1: 21, 2: 42}, 22: {1: 22, 2: 44}}

Please download the example of Dictionary in Python

Leave a Comment

Your email address will not be published. Required fields are marked *