Dictionaries
Dictionary Comprehensions
Creating dicts with comprehension syntax
Interview: Shows Pythonic fluency — dict comprehensions are used extensively in production code
Dictionary comprehensions use {key_expr: value_expr for item in iterable if condition} syntax to create dictionaries concisely. They're used for transformation, filtering, inversion, and building lookup tables.
Common Patterns
- Transform values:
{k: v*2 for k, v in d.items()} - Filter:
{k: v for k, v in d.items() if v > 0} - Invert:
{v: k for k, v in d.items()}(careful with duplicate values) - From two lists:
{k: v for k, v in zip(keys, values)} - Index lookup:
{item: i for i, item in enumerate(lst)}
Advanced Patterns
- Nested comprehension:
{k: {sk: sv for ...} for k, v in ...} - Flatten nested dict: Combine nested keys with f-strings or tuples
- With conditions on both key and value: Filter by key pattern and value range
Pitfall: Inverting Dicts
When inverting {v: k for k, v in d.items()}, duplicate values become the same key. Only the last key-value pair with that value survives. If values aren't unique, use a list-valued dict instead.
Use Cases
Building lookup tables from data
Transforming/filtering dictionary values
Creating reverse indexes and inverted mappings
Merging and flattening configuration data
Common Mistakes
Inverting dicts with duplicate values — last key wins, losing data
Writing overly complex comprehensions (>2 for/if clauses) that hurt readability
Forgetting that dict comprehension {k: v for ...} is distinct from set comprehension {x for ...}
Not using defaultdict when the comprehension logic requires accumulating values into lists