Write {key_expr: value_expr for item in iterable} (optionally appending if condition at the end to filter entries) to construct a new Python dictionary in a single, readable, C-optimized expression without pre-allocating an empty {} or calling .update() in a loop.
Basic Example
words = ["apple", "banana", "cherry", "date"]
# 1. Recommended: Map items to computed keys/values
word_lengths = {w: len(w) for w in words}
print(word_lengths)
# Output: {'apple': 5, 'banana': 6, 'cherry': 6, 'date': 4}
# 2. Filter entries with a trailing `if` clause:
long_words = {w.upper(): len(w) for w in words if len(w) >= 6}
print(long_words)
# Output: {'BANANA': 6, 'CHERRY': 6}
# 3. Transform keys/values or swap keys and values from an existing dictionary:
prices_usd = {"laptop": 1000, "mouse": 25, "keyboard": 75}
prices_discounted = {item: round(price * 0.9, 2) for item, price in prices_usd.items()}
print(prices_discounted)
# Output: {'laptop': 900.0, 'mouse': 22.5, 'keyboard': 67.5}
Key Details & Edge Cases
- Duplicate keys silently overwrite earlier entries (last write wins):
- If
key_exprproduces the same key multiple times during iteration, the later pair replaces the earlier value while keeping the key’s first-seen insertion order (e.g.,{len(w): w for w in ["cat", "dog"]}evaluates to{3: "dog"}). If you want to group all values sharing a key rather than overwriting, usecollections.defaultdict(list)ordict.setdefault().
- If
- Conditional filtering (
ifat the end) vs. conditional value assignment (if/elsebeforefor):- Place
if condafter theforclause to exclude keys from the dictionary:{k: v for k, v in items if v > 0}. - Place a ternary
val_a if cond else val_bbefore theforclause when every key stays in the dictionary and only its value varies:{k: ("pass" if score >= 50 else "fail") for k, score in grades.items()}.
- Place
- Combining two parallel sequences (
zipwithstrict=True):- Pair two lists into a dictionary via
{k: v for k, v in zip(keys, values, strict=True)}—or simplydict(zip(keys, values, strict=True)), which avoids comprehension frame overhead when no transformation or filtering is needed.
- Pair two lists into a dictionary via
- Keep key/value expressions pure and hashable:
key_exprmust evaluate to a hashable type (str,int,tuple, etc.); using alistordictaskey_exprraisesTypeError: unhashable type: 'list'. Avoid mutating external state inside comprehensions—use an explicitforloop when side effects or complextry/excepterror handling are required.
- Watch out for braces vs. sets (
{x for x in seq}vs.{k: v for ...}):- Omitting the colon
:creates a set comprehension (set), not a dictionary, and{}alone always creates an emptydict(never an emptyset).
- Omitting the colon
Comparison of Dictionary Construction Approaches in Python
| Method | Supports Key/Value Transformation & Filtering? | Speed & Readability | Best Used When |
|---|---|---|---|
{k_expr: v_expr for x in iterable if cond} (Recommended) |
Yes (arbitrary expressions + if filters) |
Fast (compiled BUILD_MAP bytecode) & very readable |
Building a dictionary by computing, transforming, inverting, or filtering items from any iterable. |
dict(zip(keys, values, strict=True)) |
No (1-to-1 pairing as-is) | Fastest (pure C constructor call) | Directly pairing two equal-length iterables of keys and values without transforming or filtering. |
dict.fromkeys(keys, default_val) |
No (single shared default value) | Fastest | Initializing all keys to an immutable default (0, None, False—never a mutable []!). |
Standard for loop with d[k] = v |
Yes (supports try/except, logging, grouping) |
Slightly slower, highest flexibility | Multi-line logic, exception handling, or accumulating lists of values per key (defaultdict(list)). |
You must log in or register to comment.
