Sub topic 5
Building dictionaries with dict comprehensions
This chapter assumes you can write for loops with range, and that you know lists, dictionaries, and sets as built-in types. It also assumes you can write boolean conditions and already know list comprehensions, including the trailing if filter and the if/else conditional expression. A dict comprehension uses the same machinery with one change: each item produces a key and a value instead of a single element.
The shape of a dict comprehension
A dict comprehension is written in curly braces. A key: value pair comes first, followed by one or more for clauses and optional if clauses.
words = ["apple", "banana", "cherry"]
lengths = {}
for w in words:
lengths[w] = len(w)
lengths = {w: len(w) for w in words}
print(lengths) # {'apple': 5, 'banana': 6, 'cherry': 6}Both versions build the same dictionary. The loop creates an empty dict and assigns one entry per iteration. The comprehension states the result directly: for every w in words, map w to len(w).
The grammar is:
{ key_expression : value_expression for target in iterable [if condition] ... }Python evaluates the pieces in this order for each item:
- The
forclause takes the next item from the iterable and binds it to the target. - Each
ifclause runs. If a condition is false, the item is skipped. - The key expression is evaluated, then the value expression. (Since Python 3.8 the key is evaluated first. Older versions evaluated the value first.)
- The pair is stored in the new dictionary. If the key is already there, the new value replaces the old one.
Iterating over an existing dictionary
The most common use is to transform another dictionary. Call .items() to get (key, value) pairs, then unpack them in the for clause.
prices = {"apple": 120, "pear": 80, "melon": 350} # prices in cents
doubled = {name: cents * 2 for name, cents in prices.items()}
print(doubled) # {'apple': 240, 'pear': 160, 'melon': 700}
names_only = {name.upper(): cents for name, cents in prices.items()}
print(names_only) # {'APPLE': 120, 'PEAR': 80, 'MELON': 350}The comprehension always creates a new dictionary. It never changes prices. If you want the original name to refer to the result, reassign it: prices = {...}.
Iterating a dict without `.items()`
Looping over a dictionary directly yields only its keys. Leaving out .items() is a common mistake:
d = {"ab": 1, "cd": 2}
print({k: v for k, v in d}) # {'a': 'b', 'c': 'd'}This ran without an error because each two-character key string was unpacked into two single characters. With any other key length, you would get a ValueError about unpacking instead. The silent version is the more dangerous one, so always check that you are iterating .items() when you need both parts.
Filtering entries
A trailing if decides which entries are included. It works exactly as it does in a list comprehension and runs before the key and value are computed.
prices = {"apple": 120, "pear": 80, "melon": 350}
cheap = {name: cents for name, cents in prices.items() if cents < 200}
print(cheap) # {'apple': 120, 'pear': 80}You can combine several conditions with and or or, or write several if clauses in a row. Consecutive if clauses behave like and.
stock = {"apple": 0, "pear": 12, "melon": 4, "fig": 30}
selected = {k: v for k, v in stock.items() if v > 0 if k != "fig"}
print(selected) # {'pear': 12, 'melon': 4}Choosing values with if/else
An if/else that appears inside the value expression chooses the value for every entry. No entries are dropped.
prices = {"apple": 120, "pear": 80, "melon": 350}
sale = {name: (cents - 20 if cents > 100 else cents) for name, cents in prices.items()}
print(sale) # {'apple': 100, 'pear': 80, 'melon': 330}The parentheses are optional but they make clear that the conditional belongs to the value and not to the whole comprehension. The same idea applies to keys, though conditional keys are rarer.
The two positions of if do different jobs, and mixing them up gives a syntax error:
| Position | Form | Effect |
|---|---|---|
| After the `for` clause | `... for k, v in d.items() if v > 0` | Drops entries that fail the test. No `else` is allowed. |
| Inside the key or value | `k: (v if v > 0 else 0)` | Keeps every entry and picks a value. `else` is required. |
d = {"a": 1, "b": -1}
# {k: v for k, v in d.items() if v > 0 else 0} # SyntaxError
print({k: v for k, v in d.items() if v > 0}) # {'a': 1}
print({k: (v if v > 0 else 0) for k, v in d.items()}) # {'a': 1, 'b': 0}Building a dictionary from other sequences
A dict comprehension is not limited to dictionary input. Any iterable works. Two combinations come up constantly.
enumerate gives you a lookup from item to position:
words = ["apple", "banana", "cherry"]
index_of = {w: i for i, w in enumerate(words)}
print(index_of) # {'apple': 0, 'banana': 1, 'cherry': 2}zip pairs two parallel sequences. This is the same job as dict(zip(a, b)), but the comprehension lets you filter or transform along the way:
names = ["ada", "grace", "linus"]
scores = [95, 88, 72]
print(dict(zip(names, scores))) # {'ada': 95, 'grace': 88, 'linus': 72}
passed = {n.title(): s for n, s in zip(names, scores) if s >= 80}
print(passed) # {'Ada': 95, 'Grace': 88}When no transformation is needed, dict(zip(names, scores)) is shorter and clearer. Use a comprehension only when you add something to it.
Duplicate keys: the last one wins
A dictionary holds each key once. If the comprehension produces the same key twice, the later value overwrites the earlier one. This matters most when you invert a mapping.
words = ["apple", "banana", "cherry"]
lengths = {w: len(w) for w in words}
print(lengths) # {'apple': 5, 'banana': 6, 'cherry': 6}
inverted = {length: w for w, length in lengths.items()}
print(inverted) # {5: 'apple', 6: 'cherry'}"banana" has been lost. Both it and "cherry" map to the key 6, and "cherry" was processed later. Python does not warn you about this.
Two details help when you debug these cases:
- The overwritten key keeps its original position in the dictionary's order. Only the value changes. Dictionaries preserve insertion order, so the position is set when the key first appears.
- Collisions can come from normalizing keys too, not only from inverting.
raw = {"Name": "Ada", "name": "Grace", "AGE": 36}
normalized = {k.lower(): v for k, v in raw.items()}
print(normalized) # {'name': 'Grace', 'age': 36}If you must keep every value, a plain dict comprehension is the wrong tool. Collect the values into lists. One compact option builds the set of keys first and then gathers matches for each. It rescans the input once per key, so for large inputs a loop with collections.defaultdict(list) is faster.
words = ["apple", "banana", "cherry"]
by_length = {n: [w for w in words if len(w) == n] for n in sorted({len(w) for w in words})}
print(by_length) # {5: ['apple'], 6: ['banana', 'cherry']}Keys must be hashable
Dictionary keys must be hashable. That means they have a hash value that never changes. Strings, numbers, and tuples of hashable items qualify. Lists, dicts, and sets do not. A comprehension that produces such a key fails when it stores the first pair.
try:
bad = {[n]: n for n in range(3)}
except TypeError as error:
print(error) # unhashable type: 'list'
good = {(n, n + 1): n for n in range(3)}
print(good) # {(0, 1): 0, (1, 2): 1, (2, 3): 2}If you need a sequence as a key, convert it to a tuple first. Convert a set to a frozenset.
Multiple for clauses
A dict comprehension can have more than one for clause. They are read in the same order as nested loops, with the first clause as the outer loop.
rows = ["a", "b"]
cols = [1, 2, 3]
cells = {f"{r}{c}": r * c for r in rows for c in cols}
print(cells) # {'a1': 'a', 'a2': 'aa', 'a3': 'aaa', 'b1': 'b', 'b2': 'bb', 'b3': 'bbb'}The equivalent loop is easy to check against it:
rows = ["a", "b"]
cols = [1, 2, 3]
cells = {}
for r in rows:
for c in cols:
cells[f"{r}{c}"] = r * c
print(cells)Dict comprehensions can also be nested to build a dictionary of dictionaries. Keep this to a single level of nesting, because the result quickly becomes hard to read.
table = {r: {c: r * c for c in range(1, 4)} for r in range(1, 4)}
print(table[2]) # {1: 2, 2: 4, 3: 6}Scope and side effects
The target variables of a comprehension live in the comprehension's own scope. They do not overwrite a variable of the same name outside it, and they are not available afterwards.
k = "outer"
squares = {k: k * k for k in range(3)}
print(squares) # {0: 0, 1: 1, 2: 4}
print(k) # outerA comprehension should only build a value. Calling a function for its side effects inside one, such as printing, writing to a file, or appending to another list, makes the code misleading, because a reader expects the only product to be the new dictionary. Use a for loop for that kind of work.
Another trap is changing the dictionary you are iterating over. Adding or removing keys of a dict while looping over it raises RuntimeError: dictionary changed size during iteration. Building a new dictionary from the old one, as a comprehension does, avoids the problem by design.
When to prefer something else
A dict comprehension fits when each input item yields at most one entry and the key and value are short expressions. A plain loop is a better fit in these cases:
- The key or value needs several statements, a
try/except, or logging. - Several inputs must merge into one entry, as in counting or grouping. Use
collections.Counterordefaultdict. - The comprehension no longer fits on about two lines.
- The same expensive call would be needed for both the key and the value. In that case, use a loop, or reuse the result with an assignment expression such as
(y := f(x))where the language version allows it.
Exercise
What does this code print, and why? words = ["tea", "cat", "dog", "bird"] result = {len(w): w for w in words} print(result)
Show answer
It prints {3: 'dog', 4: 'bird'}. The words "tea", "cat", and "dog" all have length 3, so they all produce the key 3. Each later word overwrites the value from the one before it, which leaves "dog". The key 3 keeps the position where it first appeared. The key 4 is added last with "bird".
Exercise
Given scores = {"ada": 95, "grace": 58, "linus": 72, "alan": 40}, write one dict comprehension that returns a dictionary of only the students with a score of 60 or more, mapping each name to "pass" if the score is at least 70 and "borderline" otherwise.
Show answer
result = {name: ("pass" if score >= 70 else "borderline") for name, score in scores.items() if score >= 60}. The trailing if removes entries below 60 (grace and alan). The conditional expression in the value then chooses a label for the remaining entries. The result is {'ada': 'pass', 'linus': 'pass'}, because 95 and 72 are both at least 70.
Exercise
Why does {k: v for k, v in d} give unexpected results or an error for a dictionary d, and how do you fix it?
Show answer
Iterating over a dictionary directly yields only its keys, not pairs. The unpacking k, v then tries to split each key into two parts. This raises a ValueError for most keys and silently splits two-character strings. The fix is to iterate over d.items(), which yields (key, value) pairs: {k: v for k, v in d.items()}.