Sub topic 8
Dictionary Comprehensions
A dictionary comprehension builds a new dictionary from an iterable in a single expression. This chapter assumes you know the dictionary basics from earlier chapters: literals, items(), hashable keys, and insertion order. It also assumes you can read a list comprehension and know how for loops and conditionals work.
Syntax and working model
The general form is:
{key_expr: value_expr for item in iterable if condition}Python runs it like this:
- It creates an empty dictionary.
- It takes the next item from the iterable and binds it to the loop variable.
- If an
ifclause is present and false, it skips the item. - Otherwise it evaluates
key_expr, thenvalue_expr, and stores the pair. - It repeats from step 2 until the iterable is exhausted, then returns the dictionary.
Here is the basic form, with and without a filter:
words = ["apple", "bob", "cat"]
lengths = {w: len(w) for w in words}
print(lengths) # {'apple': 5, 'bob': 3, 'cat': 3}
long_ones = {k: v for k, v in lengths.items() if v > 3}
print(long_ones) # {'apple': 5}The result's insertion order follows the order in which the source iterable produces items. A list or another dictionary gives a predictable order. A set of strings does not, because set order can change between runs.
Common patterns
Transforming values
Iterate over items() and change the value. Keep the key as it is:
stock = {"apple": 3, "pear": 5}
doubled = {k: v * 2 for k, v in stock.items()}
print(doubled) # {'apple': 6, 'pear': 10}Building from two sequences
Use zip() to pair two sequences. You can add a filter at the same time:
names = ["ana", "ben", "cy"]
scores = [90, 72, 85]
print({n: s for n, s in zip(names, scores)})
# {'ana': 90, 'ben': 72, 'cy': 85}
print({n: s for n, s in zip(names, scores) if s >= 80})
# {'ana': 90, 'cy': 85}If you do not need a filter or a transformation, dict(zip(names, scores)) is shorter and does the same job.
Inverting a dictionary
Swap the roles of key and value:
codes = {"a": 1, "b": 2, "c": 3}
inverted = {v: k for k, v in codes.items()}
print(inverted) # {1: 'a', 2: 'b', 3: 'c'}Inversion only keeps every entry if the values are unique and hashable. See the duplicate-key section below.
Filter versus conditional value
An if at the end of the comprehension decides which items are kept. A conditional expression (x if cond else y) inside the value decides which value is stored. These are different tools, and they can be combined:
scores = {"ana": 90, "ben": 72, "cy": 85}
grades = {n: ("pass" if s >= 75 else "fail") for n, s in scores.items()}
print(grades) # {'ana': 'pass', 'ben': 'fail', 'cy': 'pass'}
tiers = {n: ("high" if s >= 88 else "ok") for n, s in scores.items() if s >= 75}
print(tiers) # {'ana': 'high', 'cy': 'ok'}Several loops and nested comprehensions
A comprehension can have more than one for clause. The clauses run left to right, like nested for statements:
table = {(x, y): x * y for x in range(1, 3) for y in range(1, 3)}
print(table) # {(1, 1): 1, (1, 2): 2, (2, 1): 2, (2, 2): 4}Tuples work as keys here because they are hashable. A comprehension can also be the value of another comprehension, which builds nested dictionaries:
rows = {"r1": [1, 2, 3], "r2": [4, 5, 6]}
squares = {name: {n: n * n for n in nums} for name, nums in rows.items()}
print(squares)
# {'r1': {1: 1, 2: 4, 3: 9}, 'r2': {4: 16, 5: 25, 6: 36}}Beyond two levels, a plain loop is usually easier to read and debug.
Choosing between tools
| Task | Best fit | Why |
|---|---|---|
| Transform or filter existing entries | Dictionary comprehension | One expression, no temporary variable |
| Pair two sequences with no changes | `dict(zip(a, b))` | Shorter, same result |
| Same default value for many keys | `dict.fromkeys(keys, 0)` | No loop needed |
| Count items | `Counter` | Built for counting |
| Group items under a key | `defaultdict(list)` | One pass; a comprehension would rescan the data per key |
| Side effects such as printing or I/O | A `for` loop | A comprehension should only build a value |
Edge cases and errors
Duplicate keys: the last one wins
A comprehension does not warn you when two items produce an equal key. Each later pair replaces the earlier value, and the key keeps its original position in the order:
codes = {"a": 1, "b": 1, "c": 2}
inverted = {v: k for k, v in codes.items()}
print(inverted) # {1: 'b', 2: 'c'}The entry 1: 'a' was silently lost. If values can repeat, group them instead, for example into lists with defaultdict(list).
Unhashable keys
The key expression must produce a hashable object. A list fails at the moment the pair is stored:
pairs = [([1, 2], "a")]
try:
bad = {k: v for k, v in pairs}
except TypeError as exc:
print(exc) # unhashable type: 'list'The usual fix is to convert the key to a tuple with tuple(k).
Evaluation order of key and value
Since Python 3.8, the key is evaluated before the value. Earlier versions evaluated the value first. This matters only when the expressions have side effects, which is a reason to avoid side effects in them:
def show(label, x):
print(label)
return x
result = {show("key", 1): show("value", 2) for _ in range(1)}
# prints "key", then "value"
print(result) # {1: 2}The loop variable does not leak
A comprehension has its own scope, so its loop variable does not overwrite a variable of the same name outside it:
k = "outer"
d = {k: 1 for k in "ab"}
print(k) # outer
print(d) # {'a': 1, 'b': 1}Late binding in lambdas
A lambda stored as a value looks up the loop variable when it is called, not when it is created. By then the loop has finished:
funcs = {n: (lambda: n) for n in range(3)}
print([f() for f in funcs.values()]) # [2, 2, 2]
fixed = {n: (lambda n=n: n) for n in range(3)}
print([f() for f in fixed.values()]) # [0, 1, 2]The default argument n=n captures the current value at creation time.
The result is built eagerly
The whole dictionary is created in memory before the expression finishes. A dictionary has no lazy form like a generator expression. If you only need to loop over the pairs once, or the data is large, iterate over a generator of tuples instead of building the dictionary.
Using comprehensions with other dictionary features
Because a comprehension produces a new dictionary, you can combine it with the merge operators from the earlier chapter:
defaults = {"theme": "light", "font": 12}
user = {"font": 14}
settings = defaults | {k: v for k, v in user.items() if v is not None}
print(settings) # {'theme': 'light', 'font': 14}You can also apply a comprehension to a dictionary you already have to remove entries. This is the safe alternative to deleting keys during iteration. The original is never modified while it is being iterated, and the result is a new dictionary:
d = {"a": 1, "b": 2, "c": 3}
d = {k: v for k, v in d.items() if v % 2 == 0}
print(d) # {'b': 2}Reassigning d rebinds the name. Any other variable that still refers to the old dictionary does not see the change. If other code holds a reference and must see the change, delete from a list(d) copy of the keys instead.
Summary of key rules
- Use
items()when you need both the key and the value. - Put a filter at the end with
if, and put a choice between two values inside the value expression. - Expect later duplicate keys to replace earlier ones without any error.
- Keep key expressions hashable, and avoid side effects in key and value expressions.
- Prefer
dict(zip(...)),Counter, ordefaultdictwhen they express the task more directly.
Exercise
Given inventory = {"apple": 0, "pear": 4, "kiwi": 7}, write one dictionary comprehension that keeps only the items in stock (value greater than 0) and labels each as "low" if the count is below 5 and "ok" otherwise. What does it return?
Show answer
{k: ("low" if v < 5 else "ok") for k, v in inventory.items() if v > 0} returns {'pear': 'low', 'kiwi': 'ok'}. The trailing if removes "apple", and the conditional expression in the value chooses the label.
Exercise
What does {len(w): w for w in ["cat", "dog", "bird"]} return, and why does it lose data?
Show answer
It returns {3: 'dog', 4: 'bird'}. Both "cat" and "dog" produce the key 3. The later pair replaces the earlier value without an error, and the key 3 keeps the position it had when first inserted.
Exercise
A colleague writes handlers = {name: (lambda: name) for name in ["a", "b", "c"]}. Calling every handler returns "c". Explain why, and give a fix.
Show answer
The lambda looks up name when it is called, and by then the comprehension has finished with name set to "c". Capture the value at creation time with a default argument: {name: (lambda name=name: name) for name in ["a", "b", "c"]}.