Python Dictionary Comprehension
Python Dictionaries are data types in Python which allows us to store data in key/value pair.
This chapter will discuss the Dictionary Comprehension.
What is Dictionary Comprehension in Python?
Dictionary comprehension is an elegant and concise way to create dictionaries.
For example, create a dictionary with number-cube key/value pair.
cube_dict = dict()
for num in range(1, 11):
cube_dict[num] = num*num*num
print(cube_dict)
Now, create the dictionary in the previous program using dictionary comprehension.
cube_dict = {num: num*num*num for num in range(1, 11)}
print(cube_dict)
The output of both programs is the same:
{1: 1, 2: 8, 3: 27, 4: 64, 5: 125, 6: 216, 7: 343, 8: 512, 9: 729, 10: 1000}
The use of dictionary comprehension allowed us to create a dictionary in one line.
How to use Dictionary Comprehension
The syntax for dictionary comprehension is:
dictionary = {key: value for vars in iterable}
where:
key
is the key of the dictionary recordvalue
is the value associated to thekey
vars
are the variables used during iteration of theiterable
objectiterable
is an object which can be iterated
For example, create a new dictionary with data from another dictionary:
#item price in euros
old_price = {'pizza': 5.90, 'coffee': 1.5, 'beefsteack': 12.50}
euro_to_pound = 0.86
new_price = {item: value*euro_to_pound for (item, value) in old_price.items()}
print(new_price)
Output:
{'pizza': 5.074, 'coffee': 1.29, 'beefsteack': 10.75}
Conditionals in Dictionary Comprehension
You can add one or more conditions to the Dictionary Comprehension.
If Conditional Dictionary Comprehension
Example with only one if
in the Dictionary Comprehension:
my_dict = {'Tom': 23, 'Ryan': 12, 'Madison': 57, 'John': 56}
even_dict = {k: v for (k, v) in my_dict.items() if v % 2 == 0}
print(even_dict) # {'Ryan': 12, 'John': 56}
Only even elements were added because of the if
clause in the dictionary comprehension.
Multiple if Conditional Dictionary Comprehension
Example with multiple if
in the Dictionary Comprehension where only the items with an odd value of less than 40 are added to the new dictionary:
my_dict = {'Tom': 23, 'Ryan': 12, 'Madison': 57, 'John': 56}
new_dict = {k: v for (k, v) in my_dict.items() if v % 2 != 0 if v < 40}
print(new_dict) # {'Tom': 23}
Multiple if
in the Dictionary Comprehension are equivalent to and
operation where both conditions have to be true.
if-else Conditional Dictionary Comprehension
Example with if-else
in the Dictionary Comprehension where the items with a value of 40 or more have the value of 'old' while others have the value of 'young'.
my_dict = {'Tom': 23, 'Ryan': 12, 'Madison': 57, 'John': 56}
new_dict = {k: ('old' if v > 40 else 'young')
for (k, v) in my_dict.items()}
print(new_dict) # {'Tom': 'young', 'Ryan': 'young', 'Madison': 'old', 'John': 'old'}
if-else
in the Dictionary Comprehension are equivalent to if-else flow control.
Nested Dictionary Comprehension
Nested dictionaries can be created adding dictionary comprehensions to dictionary comprehensions.
For example, create a multiplication table in a nested dictionary, for numbers from 2 to 4.
dictionary = {
k1: {k2: k1 * k2 for k2 in range(1, 6)} for k1 in range(2, 5)
}
print(dictionary)
Output
{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}}
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)
and equivalent to:
dictionary = dict()
for k1 in range(11, 16):
dictionary[k1] = dict()
for k2 in range(1, 6):
dictionary[k1][k2] = k1*k2
print(dictionary)
Advantages of Using Dictionary Comprehension
- Dictionary comprehension greatly shortens the process of initializing dictionaries.
- Dictionary comprehension reduces lines of code while keeping the logic intact.
Disadvantages of Using Dictionary Comprehension
Dictionary comprehensions aren't always the right choice, because:
- They can sometimes make the code run slower and consume more memory.
- They can decrease the readability of the code.