Introduction
In Python, Dictionary comprehension allows you to generate dictionaries in a single line while maintaining readability and performance. It is similar to list comprehension but specifically designed for creating dictionaries.
Dictionary comprehension is widely used in data processing, web development, automation, APIs, and data analysis. It helps developers transform, filter, and generate dictionary data efficiently.
What is Dictionary Comprehension?
Dictionary comprehension is a concise way to create dictionaries using a single line of code.
Instead of writing a loop to build a dictionary, you can use dictionary comprehension to generate key-value pairs quickly.
Traditional Method
squares = {}
for num in range(1, 6):
squares[num] = num * num
print(squares)
Output:
1: 1,
2: 4,
3: 9,
4: 16,
5: 25
}
Using Dictionary Comprehension
squares = {
num: num * num
for num in range(1, 6)
}
print(squares)
Output:
1: 1,
2: 4,
3: 9,
4: 16,
5: 25
}
The result is the same, but the code is shorter and cleaner.
Why Use Dictionary Comprehension?
Dictionary comprehension offers several benefits:
- Less code
- Better readability
- Faster development
- Easy data transformation
- Efficient filtering
- Cleaner logic
Example:
Without comprehension:
students = {}
for i in range(1, 4):
students[i] = "Student " + str(i)
print(students)
With comprehension:
students = {
i: "Student " + str(i)
for i in range(1, 4)
}
print(students)
Both produce the same result.
Dictionary Comprehension Syntax
Basic Syntax
{
key_expression: value_expression
for item in iterable
}
Components
| Part | description |
|---|---|
| key_expression | Generates the key |
| value_expression | Generates the value |
| item | Current item in iteration |
| iterable | Collection being processed |
Creating a Simple Dictionary
Example:
numbers = {
num: num * 10
for num in range(1, 6)
}
print(numbers)
Output:
1: 10,
2: 20,
3: 30,
4: 40,
5: 50
}
Creating a Dictionary from a List
Example:
fruits = [
"Apple",
"Banana",
"Mango"
]
fruit_lengths = {
fruit: len(fruit)
for fruit in fruits
}
print(fruit_lengths)
Output:
‘Apple’: 5,
‘Banana’: 6,
‘Mango’: 5
}
Creating a Dictionary with String Values
Example:
students = {
num: "Student"
for num in range(1, 4)
}
print(students)
Output:
1: ‘Student’,
2: ‘Student’,
3: ‘Student’
}
Using Conditions in Dictionary Comprehension
You can filter data using an if condition.
Syntax
{
key: value
for item in iterable
if condition
}
Example: Even Numbers Only
even_squares = {
num: num * num
for num in range(1, 11)
if num % 2 == 0
}
print(even_squares)
Output:
2: 4,
4: 16,
6: 36,
8: 64,
10: 100
}
Only even numbers are included.
Using if-else in Dictionary Comprehension
You can assign different values based on conditions.
Example:
numbers = {
num: "Even"
if num % 2 == 0
else "Odd"
for num in range(1, 6)
}
print(numbers)
Output:
1: ‘Odd’,
2: ‘Even’,
3: ‘Odd’,
4: ‘Even’,
5: ‘Odd’
}
Transforming Existing Dictionaries
Dictionary comprehension can modify an existing dictionary.
Example:
prices = {
"Laptop": 50000,
"Mouse": 500
}
discounted_prices = {
item: price * 0.9
for item, price in prices.items()
}
print(discounted_prices)
Output:
‘Laptop’: 45000.0,
‘Mouse’: 450.0
}
Changing Keys
Example:
student = {
"name": "John",
"age": 20
}
uppercase_keys = {
key.upper(): value
for key, value in student.items()
}
print(uppercase_keys)
Output:
‘NAME’: ‘John’,
‘AGE’: 20
}
Changing Values
Example:
student = {
"math": 80,
"science": 90
}
updated_scores = {
subject: score + 5
for subject, score in student.items()
}
print(updated_scores)
Output:
‘math’: 85,
‘science’: 95
}
Creating a Dictionary from Two Lists
Example:
names = [
"John",
"Emma",
"Alex"
]
ages = [
20,
22,
25
]
students = {
name: age
for name, age in zip(names, ages)
}
print(students)
Output:
‘John’: 20,
‘Emma’: 22,
‘Alex’: 25
}
Nested Dictionary Comprehension
Dictionary comprehension can create nested dictionaries.
Example:
table = {
num: {
x: num * x
for x in range(1, 6)
}
for num in range(1, 4)
}
print(table)
Output:
1: {1:1, 2:2, 3:3, 4:4, 5:5},
2: {1:2, 2:4, 3:6, 4:8, 5:10},
3: {1:3, 2:6, 3:9, 4:12, 5:15}
}
Real-Life Examples:
1. Student Grades
marks = {
"John": 80,
"Emma": 95,
"Alex": 60
}
Create pass/fail results:
results = {
student: "Pass"
if score >= 70
else "Fail"
for student, score in marks.items()
}
print(results)
Output:
‘John’: ‘Pass’,
‘Emma’: ‘Pass’,
‘Alex’: ‘Fail’
}
2. Product Discounts
products = {
"Laptop": 50000,
"Phone": 30000,
"Tablet": 20000
}
Apply 10% discount:
discounted = {
item: price * 0.9
for item, price in products.items()
}
print(discounted)
3. User IDs
users = [
"john",
"emma",
"alex"
]
Generate IDs:
user_ids = {
user: index + 1
for index, user in enumerate(users)
}
print(user_ids)
Output:
‘john’: 1,
’emma’: 2,
‘alex’: 3
}
Dictionary Comprehension vs Traditional Loop
| Feature | Traditional Loop | Dictionary Comprehension |
|---|---|---|
| Lines of Code | More | Less |
| Readability | Moderate | High |
| Performance | Good | Often Better |
| Code Length | Longer | Shorter |
| Example |
squares = {}
|
squares = {
|
Advantages of Dictionary Comprehension
- Concise syntax
- Better readability
- Faster coding
- Easy filtering
- Efficient transformations
- Suitable for data processing
Common Mistakes
1. Forgetting the Colon
Incorrect:
{
num num*num
for num in range(5)
}
Correct:
{
num: num*num
for num in range(5)
}
2. Using Duplicate Keys
{
num % 2: num
for num in range(5)
}
Output:
0: 4,
1: 3
}
Duplicate keys overwrite previous values.
3. Overcomplicating Logic
Avoid large, difficult-to-read comprehensions.
Bad:
{
x: y*2 if y > 10 else y+5
for x, y in data.items()
}
If logic becomes complex, use a regular loop.
4. Forgetting items() When Accessing Keys and Values
Incorrect:
{
key: value
for key, value in dictionary
}
Correct:
{
key: value
for key, value in dictionary.items()
}
Best Practices
1. Keep Comprehensions Simple
{
num: num*num
for num in range(5)
}
2. Use Meaningful Variable Names
{
student: score
for student, score in marks.items()
}
3. Use Conditions Carefully
{
num: num
for num in range(10)
if num % 2 == 0
}
Switch to Loops for Complex Logic
If readability suffers, use a standard loop instead.
Conclusion
Dictionary comprehension is a powerful Python feature that allows developers to create, transform, and filter dictionaries using concise and readable code. It reduces the need for lengthy loops while improving code maintainability and efficiency.
By mastering dictionary comprehension, you can perform data transformations, filtering, key-value generation, and dictionary manipulation more effectively. Whether you’re working with APIs, databases, automation scripts, or data analysis projects, dictionary comprehension is an essential tool that can help you write cleaner and more professional Python code.