Dictionary Comprehensions in Python
Dictionary comprehensions create dictionaries in a single line using concise syntax. They're more readable and often faster than traditional loops for building dictionaries.
Basic Syntax
# Traditional loop
squares = {}
for x in range(5):
squares[x] = x ** 2
# Dictionary comprehension
squares = {x: x**2 for x in range(5)}
# Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
From Two Lists
keys = ['name', 'age', 'city']
values = ['Alice', 30, 'NYC']
# Create dictionary from two lists
person = {k: v for k, v in zip(keys, values)}
# Output: {'name': 'Alice', 'age': 30, 'city': 'NYC'}
With Conditional Logic
# Filter: Only even numbers
numbers = range(10)
evens = {x: x**2 for x in numbers if x % 2 == 0}
# Output: {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
# If-else in value
labels = {x: 'even' if x % 2 == 0 else 'odd' for x in range(5)}
# Output: {0: 'even', 1: 'odd', 2: 'even', 3: 'odd', 4: 'even'}
Transform Existing Dictionary
Swap Keys and Values
original = {'a': 1, 'b': 2, 'c': 3}
swapped = {v: k for k, v in original.items()}
# Output: {1: 'a', 2: 'b', 3: 'c'}
Filter Dictionary
prices = {'apple': 0.50, 'banana': 0.30, 'orange': 0.80, 'grape': 0.20}
# Only items over $0.40
expensive = {k: v for k, v in prices.items() if v > 0.40}
# Output: {'apple': 0.50, 'orange': 0.80}
Modify Values
prices = {'apple': 0.50, 'banana': 0.30, 'orange': 0.80}
# Apply 10% discount
discounted = {k: v * 0.9 for k, v in prices.items()}
# Output: {'apple': 0.45, 'banana': 0.27, 'orange': 0.72}
Nested Dictionary Comprehension
# Create multiplication table
table = {
i: {j: i*j for j in range(1, 4)}
for i in range(1, 4)
}
# Output: {1: {1: 1, 2: 2, 3: 3},
# 2: {1: 2, 2: 4, 3: 6},
# 3: {1: 3, 2: 6, 3: 9}}
Practical Examples
Word Frequency Counter
text = "the quick brown fox jumps over the lazy dog"
words = text.split()
# Count word frequencies
freq = {word: words.count(word) for word in set(words)}
# Output: {'the': 2, 'quick': 1, 'brown': 1, ...}
Group Data by Category
students = [
{'name': 'Alice', 'grade': 'A'},
{'name': 'Bob', 'grade': 'B'},
{'name': 'Charlie', 'grade': 'A'}
]
# Group names by grade
by_grade = {
grade: [s['name'] for s in students if s['grade'] == grade]
for grade in set(s['grade'] for s in students)
}
# Output: {'A': ['Alice', 'Charlie'], 'B': ['Bob']}
Clean and Normalize Data
raw_data = {' Name ': 'Alice', 'AGE ': '30', ' City': 'NYC '}
# Clean keys and values
clean = {k.strip().lower(): v.strip() for k, v in raw_data.items()}
# Output: {'name': 'Alice', 'age': '30', 'city': 'NYC'}
When to Use Dict Comprehensions
- Creating dictionaries from sequences
- Transforming existing dictionaries
- Filtering dictionary items
- Simple one-to-one mappings
Pro Tip: Dict comprehensions are great for simple transformations. For complex logic, use regular loops for better readability. Remember: readable code beats clever one-liners!
← Back to Python Tips