Introduction
Like list comprehension, Dictionary Comprehension is one of the exclusive features of Python Programming 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 you again, our topic of discussion today is Dictionary Comprehension in Python. Here, we will learn the entire topic by solving several programming examples.
What is dictionary comprehension?
It's similar to list comprehension in python which allows writing code in a compact form or fewer lines. See the image below for a better understanding.
Difference between Dictionary Comprehension and the traditional method |
The syntax
The syntax for the Dictionary Comprehension method looks like the following.
dict_var = {key: expression for item in iterable}
or
dict_var = {key: expression for item in iterable conditional statements}
Let's solve a problem with and without using Dictionary Comprehension. It will help you to understand the logic better.
Problem
Store the square of each item between 1 and 8 and store the results in a python dictionary.
Solution 1: Without using Dictionary Comprehension
First, we will follow the normal method to solve this problem.
# 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: Using Dictionary Comprehension
Now, we will solve the same problem but applying Dictionary Comprehension, and see what's the difference.
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
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.
# 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 Python Dictionary for each number between 1 and 10.
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
1 : odd
2 : even
3 : odd
4 : even
5 : odd
6 : even
7 : odd
8 : even
9 : odd
10 : even
Nested Dictionary Comprehension
Here, we'll create a nested Dictionary using the Dictionary Comprehension technique.
# 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}
Keep in Mind
Although the dictionary comprehension method helps to write code in fewer lines and gives a better look, try not to follow this way for complex problems as it reduces the readability of the code.
Summary
In this tutorial, you have learned dictionary comprehension in Python with various programming examples. I hope now the logic is very clear to you and now you can do it yourself.
For any queries related to this topic, just leave your comment below. You will get an immediate response.
Thanks for reading!
PySeek