Dict comprehensions are Python’s concise, expressive way to create new dictionaries from iterables — similar to list comprehensions but producing key-value pairs instead of single values. The syntax {key_expr: value_expr for item in iterable if condition} lets you transform, filter, and build dicts in a single readable line. In 2026, dict comprehensions are essential — used constantly for data restructuring, filtering JSON/API results, creating lookup tables, inverting mappings, and preparing data for pandas/Polars or databases.
Here’s a complete, practical guide to dict comprehensions: basic creation, filtering, real-world patterns, conditional values, and modern best practices with type hints, readability, and when to avoid them.
The basic form generates a dictionary by mapping each item to a key and value expression — no loops or temporary variables needed.
# Squares of numbers 1 to 10
numbers = range(1, 11)
squares_dict = {num: num ** 2 for num in numbers}
print(squares_dict)
# {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}
Add a condition with if at the end — only items that pass are included in the dictionary.
# Only even numbers ? square as value
even_squares = {num: num ** 2 for num in range(1, 11) if num % 2 == 0}
print(even_squares)
# {2: 4, 4: 16, 6: 36, 8: 64, 10: 100}
Real-world pattern: restructuring or filtering data — very common when processing JSON, API responses, CSV rows, or config objects.
raw_data = [
{"id": 1, "name": "Alice", "active": True},
{"id": 2, "name": "Bob", "active": False},
{"id": 3, "name": "Charlie", "active": True}
]
# Active users: id ? name
active_users = {user["id"]: user["name"] for user in raw_data if user["active"]}
print(active_users) # {1: 'Alice', 3: 'Charlie'}
# Invert mapping: name ? id
name_to_id = {user["name"]: user["id"] for user in raw_data}
print(name_to_id) # {'Alice': 1, 'Bob': 2, 'Charlie': 3}
Use conditional expressions (value_if_true if condition else value_if_false) to transform values differently — instead of filtering out items.
words = ["apple", "banana", "cherry", "durian"]
# Vowel-starting words ? length, others ? 'skipped'
vowel_lengths = {word: len(word) if word[0].lower() in 'aeiou' else 'skipped'
for word in words}
print(vowel_lengths)
# {'apple': 5, 'banana': 'skipped', 'cherry': 'skipped', 'durian': 6}
Best practices keep dict comprehensions readable, efficient, and safe. Keep them short — one key/value expression, one if at most; if logic grows (>1–2 lines, nested conditions, try/except), switch to a regular for loop. Use meaningful variable names — {user_id: name for user_id, name in users.items() if active} — never cryptic {k:v for k,v in d.items()}. Add type hints for clarity — dict[int, str] or dict[str, Any] — improves readability and IDE/mypy support. Avoid side effects inside comprehensions — no print(), file writes, or database calls; keep them pure. Modern tip: use dict union ({**d1, **d2} or d1 | d2 in 3.9+) for merging while comprehending. In production, when comprehending external data (API responses, JSON), wrap in try/except — handle missing keys or type mismatches gracefully. Prefer comprehensions for data restructuring/filtering — they’re often 2–5× faster than equivalent loops.
Dict comprehensions are Python’s concise way to build or transform dictionaries — fast, expressive, and elegant for mapping, filtering, and restructuring. In 2026, use them with type hints, keep them simple, and switch to loops for complex logic. Master dict comprehensions, and you’ll handle JSON, configs, lookups, and data prep with speed and clarity.
Next time you need a new dictionary from an iterable — reach for a dict comprehension. It’s Python’s cleanest way to say: “Map these keys to these values, with these rules.”