Dictionary comprehension in Python lets you create dictionaries in a single line of code. It’s like a shortcut that makes your code cleaner and often faster. While many Python developers know about list comprehension, dictionary comprehension is just as useful but often overlooked.
This guide will show you exactly how to use dictionary comprehension – from the basics to advanced techniques. Let’s make Python coding easier and more efficient.
Table of Contents
- What is Dictionary Comprehension?
- Common Dictionary Comprehension Patterns
- Adding Conditions
- Real-World Examples
- Advanced Uses
- Making Your Code Better
- Tips for Success
- Common Mistakes to Avoid
- Wrapping Up
What is Dictionary Comprehension?
Think of dictionary comprehension as a recipe that turns other data into a dictionary. Instead of writing several lines with loops, you can create a dictionary in just one line.
Here’s what it looks like:
# Basic pattern
new_dict = {key: value for item in collection}
Code language: PHP (php)
Let’s see it in action:
# Making a dictionary of numbers and their squares
numbers = [1, 2, 3, 4, 5]
squares = {num: num**2 for num in numbers}
print(squares) # Shows: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Code language: PHP (php)
Common Dictionary Comprehension Patterns
Creating from Two Lists
Here’s how to pair up two lists into a dictionary:
names = ['Alice', 'Bob', 'Charlie']
grades = [95, 87, 92]
student_grades = {name: grade for name, grade in zip(names, grades)}
print(student_grades) # Shows: {'Alice': 95, 'Bob': 87, 'Charlie': 92}
Code language: PHP (php)
Changing Dictionary Values
You can update all values in a dictionary at once:
prices = {'apple': 1, 'banana': 2, 'orange': 3}
sale_prices = {item: price * 0.8 for item, price in prices.items()}
print(sale_prices) # Shows discounted prices
Code language: PHP (php)
Adding Conditions
Simple Filtering
# Keep only even numbers
numbers = range(10)
even_squares = {n: n**2 for n in numbers if n % 2 == 0}
print(even_squares) # Shows even numbers and their squares
Code language: PHP (php)
If-Else Conditions
numbers = range(1, 6)
status = {n: 'even' if n % 2 == 0 else 'odd' for n in numbers}
print(status) # Shows which numbers are odd or even
Code language: PHP (php)
Real-World Examples
Data Cleaning
# Clean up messy data
raw_data = {'name': ' John ', 'age': '25', 'city': ' NEW YORK '}
clean_data = {k: v.strip().title() if isinstance(v, str) else v
for k, v in raw_data.items()}
print(clean_data) # Shows cleaned up data
Code language: PHP (php)
Working with Files
# Create a dict of file names and sizes
import os
files = os.listdir('.')
file_sizes = {f: os.path.getsize(f) for f in files if os.path.isfile(f)}
Code language: PHP (php)
Advanced Uses
Nested Dictionaries
# Create a multiplication table
table = {i: {j: i*j for j in range(1, 4)} for i in range(1, 4)}
print(table) # Shows a neat multiplication table
Code language: PHP (php)
Working with Objects
class Book:
def __init__(self, title, price):
self.title = title
self.price = price
books = [Book('Python Basic', 29.99), Book('Data Science', 39.99)]
book_prices = {book.title: book.price for book in books}
Making Your Code Better
When to Use It
- Creating dictionaries from lists or other data
- Updating dictionary values
- Filtering dictionary items
- Simple data transformations
When Not to Use It
- Complex operations with multiple steps
- Code that needs lots of error handling
- When regular loops are easier to read
Tips for Success
- Keep it simple
- Use clear variable names
- Add comments for complex operations
- Test with small data first
- Watch out for memory usage with big data sets
Common Mistakes to Avoid
Duplicate Keys
# Last value wins for duplicate keys
values = [1, 2, 2, 3, 3, 3]
result = {x: x**2 for x in values} # Some values will be lost
Code language: PHP (php)
Memory Issues
# Be careful with large ranges
# This might use too much memory:
big_dict = {x: x**2 for x in range(1000000)}
Code language: PHP (php)
Wrapping Up
Dictionary comprehension makes Python code shorter and often faster. Start with simple examples and gradually try more complex ones. Remember that clear code is better than clever code – use dictionary comprehension when it makes your code easier to understand, not harder.
Practice with these examples, and soon you’ll be using dictionary comprehension naturally in your Python projects. Keep experimenting, and you’ll find more ways to make your code better and more efficient.