Yes! Python supports dictionary comprehensions, which use a syntax similar to list comprehensions but generate dictionaries instead. Here’s how they work:
Basic Syntax
{key_expression: value_expression for item in iterable}
Examples
1. Create a Dictionary of Squares
squares = {x: x ** 2 for x in range(5)}
# Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
2. Convert List of Tuples to a Dictionary
data = [("a", 1), ("b", 2), ("c", 3)]
dict_from_tuples = {k: v for k, v in data}
# Output: {'a': 1, 'b': 2, 'c': 3}
3. Filter Items with a Condition
even_numbers = {x: x * 2 for x in range(10) if x % 2 == 0}
# Output: {0: 0, 2: 4, 4: 8, 6: 12, 8: 16}
4. Transform Keys/Values
words = ["apple", "banana", "cherry"]
lengths = {word.upper(): len(word) for word in words}
# Output: {'APPLE': 5, 'BANANA': 6, 'CHERRY': 6}
5. 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'}
Key Features
- Conditionals: Use
if
to filter items. - Nested Loops: Combine multiple iterables.
- Efficiency: Concise and performant for simple transformations.
Nested Comprehension Example
# Create a grid of coordinates
grid = {(x, y): x + y for x in range(3) for y in range(3)}
# Output: {(0,0): 0, (0,1): 1, (0,2): 2, (1,0): 1, ...}
When to Avoid
For complex logic, use a traditional loop for clarity:
# Hard-to-read comprehension:
result = {k: (v if v > 0 else None) for k, v in data if k.startswith('valid_')}
# Clearer with a loop:
result = {}
for k, v in data:
if k.startswith('valid_'):
result[k] = v if v > 0 else None
Summary
- Dictionary comprehensions are concise and powerful for creating dictionaries.
- Use them for simple mappings, filtering, or transformations.
- Opt for loops if the logic becomes too complex.