Python Dictionary and Set Comprehensions
What you will learn
- The three shapes:
[...],{k: v ...}and{x ...} - Dictionary comprehensions: transform, filter, rename, invert, look up
- Set comprehensions: unique and normalised items
- What happens when keys collide
- Why there is no tuple comprehension
- The syntax errors to avoid
1. Three shapes
You know the list comprehension (lessons 12.1 and 12.2). The same idea builds dictionaries and sets; only the brackets and the first part change:
| Builds | Shape | First part |
|---|---|---|
| a list | [expression for item in iterable] |
one value |
| a dictionary | {key: value for item in iterable} |
a key and a value, joined by a colon |
| a set | {expression for item in iterable} |
one value (no colon) |
words = ["apple", "fig", "kiwi", "banana", "fig"]
print([len(w) for w in words])
print({w: len(w) for w in words})
print({len(w) for w in words} == {3, 4, 5, 6})
[5, 3, 4, 6, 3]
{'apple': 5, 'fig': 3, 'kiwi': 4, 'banana': 6}
True
- The list keeps every item, including the repeated
fig. - The dictionary has each word once: the second
figoverwrote the first with the same value. - The set keeps the distinct lengths.
The colon is what makes it a dictionary. {x for ...} is a set, and {k: v for ...} is a dictionary. (An empty {} is always a dictionary, lesson 10.1.)
Quick check: what is `{n: n * 2 for n in range(3)}`?
{0: 0, 1: 2, 2: 4}.
2. Dictionary comprehensions
From a sequence
print({n: n * n for n in range(1, 6)})
print({n: n * n for n in range(1, 11) if n % 2 == 0})
print({c: ord(c) for c in "abc"})
print({i: c for i, c in enumerate("abc")})
print({c: i for i, c in enumerate("abc")})
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
{2: 4, 4: 16, 6: 36, 8: 64, 10: 100}
{'a': 97, 'b': 98, 'c': 99}
{0: 'a', 1: 'b', 2: 'c'}
{'a': 0, 'b': 1, 'c': 2}
The last two show how to make a position-to-item table, and its opposite (the item to its position).
From another dictionary
Loop over .items() to transform, filter, rename or invert a dictionary (lesson 9.3):
d = {"a": 1, "b": 2, "c": 3}
print({k: v * 10 for k, v in d.items()})
print({k: v for k, v in d.items() if v > 1})
print({k.upper(): v for k, v in d.items()})
print({v: k for k, v in d.items()})
print({k: ("big" if v > 1 else "small") for k, v in d.items()})
{'a': 10, 'b': 20, 'c': 30}
{'b': 2, 'c': 3}
{'A': 1, 'B': 2, 'C': 3}
{1: 'a', 2: 'b', 3: 'c'}
{'a': 'small', 'b': 'big', 'c': 'big'}
| Goal | Change |
|---|---|
| change values | the part after the colon |
| change keys | the part before the colon |
| drop pairs | an if at the end |
| swap keys and values | {v: k for k, v in d.items()} (needs unique, hashable values) |
| label values | a conditional expression after the colon |
To pick some keys, loop over the keys you want:
print({k: d[k] for k in d if k != "b"})
print({k: d[k] for k in ["a", "c"]})
print({k: d.get(k, 0) for k in "abz"})
{'a': 1, 'c': 3}
{'a': 1, 'c': 3}
{'a': 1, 'b': 2, 'z': 0}
The last one asks for "z", which is missing, so get gives the default 0 (lesson 9.1).
From two lists, or pairs
print({k: v for k, v in zip("abc", range(3))})
print({k: v for k, v in [("x", 1), ("y", 2), ("x", 3)]})
{'a': 0, 'b': 1, 'c': 2}
{'x': 3, 'y': 2}
In the second line the pair ("x", 3) came later and replaced ("x", 1): keys must be unique, so the last value wins.
3. Lookup tables from records
A very common use: index a list of records by an id, so that you can find one instantly (lesson 9.4):
people = [{"id": 7, "name": "Rina"}, {"id": 9, "name": "Sam"}]
print({p["id"]: p["name"] for p in people})
print({p["id"]: p for p in people}[9])
print({p["name"]: p["id"] for p in people})
{7: 'Rina', 9: 'Sam'}
{'id': 9, 'name': 'Sam'}
{'Rina': 7, 'Sam': 9}
{p["id"]: p for p in people} keeps the whole record as the value, so table[9] finds Sam's record without searching the list.
A letter-to-number table:
lookup = {c: i for i, c in enumerate("abcdefghijklmnopqrstuvwxyz", 1)}
print([lookup[c] for c in "cab"], sum(lookup[c] for c in "abc"))
[3, 1, 2] 6
4. Nested dictionaries
The value can itself be a comprehension:
nested = {n: {m: n * m for m in range(1, 3)} for n in range(1, 3)}
print(nested)
print(nested[2][2])
print({k: sum(v.values()) for k, v in nested.items()})
{1: {1: 1, 2: 2}, 2: {1: 2, 2: 4}}
4
{1: 3, 2: 6}
Keys may be tuples (they are hashable, lesson 9.7). Two for parts give pairs:
print({(x, y): x * y for x in range(2) for y in range(2)})
{(0, 0): 0, (0, 1): 0, (1, 0): 0, (1, 1): 1}
Be careful: {x: y for x in range(2) for y in range(2)} gives {0: 1, 1: 1}, because each x is written twice and the last y wins.
5. Summarising groups
When the values are lists, a comprehension can summarise each one:
scores = {"Rina": [90, 80], "Sam": [70, 60, 50]}
print({n: sum(s) / len(s) for n, s in scores.items()})
print({n: max(s) for n, s in scores.items()})
print({n: len(s) for n, s in scores.items()})
print({n for n, s in scores.items() if len(s) > 2})
{'Rina': 85.0, 'Sam': 60.0}
{'Rina': 90, 'Sam': 70}
{'Rina': 2, 'Sam': 3}
{'Sam'}
The last line is a set comprehension: the names of those with more than two scores.
For counting, collections.Counter (lesson 9.6) is better than counting inside a comprehension, because {w: words.count(w) for w in words} searches the whole list again for every word. A comprehension then filters the counts:
import collections
counts = collections.Counter(words)
print({w: c for w, c in counts.items() if c > 1})
{'fig': 2}
6. Set comprehensions
A set comprehension builds a set: its items are unique and unordered (lesson 10.1). It is ideal for distinct and normalised values:
print(sorted({s.lower() for s in ["A", "a", "B"]}))
print(sorted({w.strip().lower() for w in [" Fig", "fig ", "KIWI", "kiwi"]}))
print(sorted({c for c in "Mississippi".lower() if c not in "aeiou"}))
print({n % 3 for n in range(10)})
print(len({n for n in [3, 1, 3, 2, 1]}))
['a', 'b']
['fig', 'kiwi']
['m', 'p', 's']
{0, 1, 2}
3
Normalise first (strip, lower), and the duplicates that differ only in case or spaces collapse into one. sorted is used here only to show the result in a fixed order, since a set has none.
A set comprehension is also a good way to build a fast membership table:
allowed = {w.lower() for w in ["Fig", "Kiwi"]}
print("fig" in allowed, "plum" in allowed)
True False
7. Errors and traps
Unhashable keys and items. A key (or a set item) must be hashable (lesson 9.7):
{[1]: 2 for _ in range(1)}
TypeError: unhashable type: 'list'
The same happens for a set of lists. Use tuples instead.
Syntax slips. A dictionary comprehension needs both a key and a value, separated by a colon:
| Mistake | Result |
|---|---|
{k: for k in 'ab'} |
SyntaxError |
{k: v for k in 'ab'} |
NameError: v was never defined |
Collisions. When two items give the same key, the later one wins and an item is lost, silently. If you need all of them, group into lists with defaultdict(list) (lesson 9.6), as inverting does: {v: k for k, v in d.items()} loses keys when the values repeat.
Order. A dictionary comprehension keeps insertion order (lesson 9.5). A set comprehension has no order. To get a dictionary in a sorted order, build it from sorted pairs:
print({k: v for k, v in sorted(d.items(), key=lambda kv: -kv[1])})
{'c': 3, 'b': 2, 'a': 1}
8. There is no tuple comprehension
Round brackets do not make a tuple comprehension. They make a generator expression (lesson 12.6), which produces its items one at a time:
g = (n * n for n in range(3))
print(type(g).__name__)
print(list(g))
print(tuple(n * n for n in range(3)))
generator
[0, 1, 4]
(0, 1, 4)
To get a tuple from a comprehension, pass a generator expression to tuple(...).
Worked example: a small grade book
From a list of student records, build an id table, a table of averages, a set of students who need help, and a count of grades.
students = [
{"id": 1, "name": "Rina", "marks": [90, 85]},
{"id": 2, "name": "Sam", "marks": [55, 40, 62]},
{"id": 3, "name": "Lee", "marks": [72]},
]
by_id = {s["id"]: s["name"] for s in students}
average = {s["name"]: round(sum(s["marks"]) / len(s["marks"]), 1) for s in students}
needs_help = {s["name"] for s in students if min(s["marks"]) < 50}
grade = {name: ("A" if avg >= 85 else "B" if avg >= 70 else "C") for name, avg in average.items()}
by_grade = {g: [n for n, x in grade.items() if x == g] for g in sorted(set(grade.values()))}
print(by_id)
print(average)
print(needs_help)
print(grade)
print(by_grade)
{1: 'Rina', 2: 'Sam', 3: 'Lee'}
{'Rina': 87.5, 'Sam': 52.3, 'Lee': 72.0}
{'Sam'}
{'Rina': 'A', 'Sam': 'C', 'Lee': 'B'}
{'A': ['Rina'], 'B': ['Lee'], 'C': ['Sam']}
| Result | Kind | How |
|---|---|---|
by_id |
dictionary | id → name |
average |
dictionary | name → average, rounded |
needs_help |
set | names whose lowest mark is under 50 |
grade |
dictionary | a choice in the value |
by_grade |
dictionary of lists | a list comprehension inside the value |
Each comprehension is one clear line. The names and marks are made up.
Common mistakes
- Forgetting the colon for a dictionary (you get a set), or writing a key with no value.
- Using unhashable keys (lists, sets, dictionaries).
- Losing data to key collisions without noticing.
- Expecting a set comprehension to be ordered.
- Counting with
list.countinside a comprehension, which repeats the search for every item. UseCounter. - Looking for a tuple comprehension. Use
tuple(... for ...).
Key takeaways
{k: v for ...}builds a dictionary;{x for ...}builds a set; the colon is the difference.- Loop over
d.items()to transform values or keys, filter withif, label with a conditional expression, or invert (if values are unique). - Later pairs overwrite earlier ones with the same key, silently.
- Sets built by comprehension are unique and unordered: normalise first, then take distinct.
- Round brackets make a generator expression, not a tuple; use
tuple(...)to get a tuple.
Practice
1. Make {"a": 1, "b": 2, "c": 3} from the string "abc" using enumerate starting at 1.
Show answer
{c: i for i, c in enumerate("abc", 1)}.
2. From prices = {"tea": 2, "milk": 1.5, "oil": 8}, keep the items that cost less than 5.
Show answer
{k: v for k, v in prices.items() if v < 5} gives {'tea': 2, 'milk': 1.5}.
3. Make a set of the lower-case first letters of ["Apple", "avocado", "Banana"].
Show answer
{w[0].lower() for w in ["Apple", "avocado", "Banana"]} gives {'a', 'b'}.
4. Why does {v: k for k, v in {"a": 1, "b": 1}.items()} lose a pair?
Show answer
Both values are 1, so after swapping they are the same key, and the later pair overwrites the earlier one: {1: 'b'}.
5. How do you get a tuple of the squares of 1 to 4?
Show answer
tuple(n * n for n in range(1, 5)) gives (1, 4, 9, 16). Round brackets alone make a generator, not a tuple.
6. Index a list of dictionaries rows (each with an "id") by id.
Show answer
{row["id"]: row for row in rows}.