Introduction
As like the list comprehension method, dictionary comprehension is one of the exclusive features of python language which helps to write code in a compact form or fewer lines. But before we move on, I'm highly recommending you, please learn about Python Dictionary if you are not so familiar with this beautiful thing of python.
So let's remind again, our topic of discussion today is Dictionary Comprehension in Python.
What is dictionary comprehension?
It's similar to list comprehension in python which allows writing code in a compact for or less line.
Let's solve a problem with and without dictionary comprehension. It would help you to understand the logic better.
Problem: Store the square value of each item between 1 and 8 and store the results in a python dictionary.
Solution 1: Without Comprehension
Code
# declaring a dictionary variable
square = dict()
for data in range(1, 9):
square[data] = data**2
# Printing the results
for key, res in square.items():
print(f"{key} : {res}")
Output
1 : 1
2 : 4
3 : 9
4 : 16
5 : 25
6 : 36
7 : 49
8 : 64
Solution 2: With Dictionary Comprehension
Code
square = {f"Square of {num} is":num**2 for num in range(1,9)}
for key, res in square.items():
print(f"{key}: {res}")
Output
Square of 1 is: 1
Square of 2 is: 4
Square of 3 is: 9
Square of 4 is: 16
Square of 5 is: 25
Square of 6 is: 36
Square of 7 is: 49
Square of 8 is: 64
The syntax
dict_var = {key: expression for item in iterable}
or
dict_var = {key: expression for item in iterable conditional statements}
Dictionary Comprehension with count method
Problem: Count the number of occurrences of each character in a word and store the result in a python dictionary.
Code
# Character Count
name = "google"
char_count = {char:name.count(char) for char in name}
print(char_count)
Output
{'g': 2, 'o': 2, 'l': 1, 'e': 1}
Dictionary Comprehension with if else
Problem: Store even or odd status in a dictionary for each item between 1 and 10.
Code
odd_even={num: ('even' if num%2==0 else 'odd') for num in range(1,11)}
for key, res in odd_even.items():
print(f"{key} : {res}")
Output
Nested Dictionary Comprehension
Here, we'll nest one dictionary to another using the comprehension technique.
Code
# nested dictionary comprehension python
nes_dict={i: {num:num*2 for num in range(4, 8)} for i in range(0,4)}
for key, res in nes_dict.items():
print(f"{key} : {res}")
Output
0 : {4: 8, 5: 10, 6: 12, 7: 14}
1 : {4: 8, 5: 10, 6: 12, 7: 14}
2 : {4: 8, 5: 10, 6: 12, 7: 14}
3 : {4: 8, 5: 10, 6: 12, 7: 14}