Sub topic 7
Building nested structures with comprehensions and defaultdict
Earlier chapters covered reading and changing nested data that already exists. Most real programs have to build it first, from rows of input, parallel lists, or a stream of events. This chapter covers the tools for that: list and dictionary comprehensions, setdefault(), and collections.defaultdict.
This chapter assumes you can write a for loop, use zip() and enumerate(), and read a basic comprehension such as [x * 2 for x in numbers]. It also assumes you have used chained indexing like data["a"][0].
Two jobs: shaping and grouping
Building nested data usually falls into one of two jobs.
- Shaping means you already have all the data and want to turn it into a new structure. Comprehensions fit this job well.
- Grouping means you process items one at a time and file each one under a key. The inner container may not exist yet when the first item arrives.
setdefault()anddefaultdictfit this job well.
List comprehensions that produce lists of lists
A comprehension can produce an element that is itself a comprehension. The outer comprehension builds the rows, and the inner one builds the cells in each row.
table = [[row * col for col in range(1, 4)] for row in range(1, 4)]
print(table)
# [[1, 2, 3], [2, 4, 6], [3, 6, 9]]Read it from the outside in. for row in range(1, 4) runs once per row, and for each row the expression [row * col for col in range(1, 4)] builds one inner list.
A comprehension with two for clauses in a single pair of brackets is different. It produces one flat list, and the clauses appear in the same order as the equivalent nested loops.
table = [[1, 2, 3], [2, 4, 6], [3, 6, 9]]
flat = [value for row in table for value in row]
print(flat)
# [1, 2, 3, 2, 4, 6, 3, 6, 9]If you want nesting preserved, use brackets inside the expression. If you want it removed, use two for clauses in one comprehension.
Building records from parallel data
Data often arrives as separate lists that line up by position. zip() pairs them up, and a comprehension turns each pair into a dictionary.
names = ["Ana", "Ben"]
scores = [[90, 85], [70, 88, 92]]
students = [{"name": n, "grades": g} for n, g in zip(names, scores)]
print(students)
# [{'name': 'Ana', 'grades': [90, 85]}, {'name': 'Ben', 'grades': [70, 88, 92]}]The result is the list-of-dicts-holding-lists shape from the nesting chapter. Each g is the same list object that sits in scores, so students and scores now share those inner lists. The shared reference chapter covers what that means. For now, treat the inner lists as borrowed.
Dictionary comprehensions
A dictionary comprehension builds a dictionary from key: value pairs. The value can be any expression, including a list, a dictionary, or another comprehension.
students = [
{"name": "Ana", "grades": [90, 85]},
{"name": "Ben", "grades": [70, 88, 92]},
]
averages = {s["name"]: round(sum(s["grades"]) / len(s["grades"]), 1) for s in students}
print(averages)
# {'Ana': 87.5, 'Ben': 83.3}
high = {s["name"]: [g for g in s["grades"] if g >= 85] for s in students}
print(high)
# {'Ana': [90, 85], 'Ben': [88, 92]}The second comprehension is a dictionary of lists. A list comprehension nested inside a dictionary comprehension filters each student's grades.
A common use is indexing a list of records by one field, so you can look records up by name instead of scanning the list.
by_name = {s["name"]: s for s in students}
print(by_name["Ben"]["grades"][0])
# 70This produces a dictionary of dictionaries. Each value is the same record object as in students, not a copy. If a key repeats, the later record silently overwrites the earlier one.
Grouping by hand, then with setdefault()
Grouping cannot be a plain comprehension in the usual case. Each item must be appended to a list that may not exist yet. The direct approach checks first.
words = ["apple", "avocado", "banana", "blueberry", "cherry"]
groups = {}
for word in words:
letter = word[0]
if letter not in groups:
groups[letter] = []
groups[letter].append(word)
print(groups)
# {'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}The dict.setdefault(key, default) method folds the check and the assignment into one call. It returns the existing value if the key is present. Otherwise it stores default, then returns it.
groups = {}
for word in words:
groups.setdefault(word[0], []).append(word)
print(groups)
# {'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}setdefault() evaluates its second argument on every call. The expression [] builds a new empty list each time, and Python throws it away whenever the key already exists. That is harmless for small data, but it is wasted work in a hot loop.
Grouping with defaultdict
A defaultdict is a dictionary subclass that takes a factory, a callable with no arguments. When you look up a missing key with d[key], the defaultdict calls the factory, stores the result under that key, and returns it. The defaultdict is created once, and the factory runs only when a key is actually missing.
from collections import defaultdict
words = ["apple", "avocado", "banana", "blueberry", "cherry"]
by_letter = defaultdict(list)
for word in words:
by_letter[word[0]].append(word)
print(dict(by_letter))
# {'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}Different factories give different inner containers.
| Factory | Missing key becomes | Typical use |
|---|---|---|
| `list` | `[]` | Grouping items under a key |
| `set` | `set()` | Grouping without duplicates |
| `int` | `0` | Counting |
| `dict` | `{}` | Two-level dictionaries filled by hand |
| `lambda: defaultdict(int)` | a counting dictionary | Counting by two keys |
Counting is the same pattern with int. Because int() returns 0, the += works on the first occurrence.
from collections import defaultdict
counts = defaultdict(int)
for word in ["apple", "avocado", "banana", "blueberry", "cherry"]:
counts[word[0]] += 1
print(dict(counts))
# {'a': 2, 'b': 2, 'c': 1}Two levels deep
To group by two keys, the factory for the outer dictionary must itself produce a defaultdict. The factory has to be callable with no arguments, so wrap the inner construction in a lambda.
from collections import defaultdict
sales = [
("north", "apple", 3),
("north", "pear", 2),
("south", "apple", 5),
("north", "apple", 4),
]
totals = defaultdict(lambda: defaultdict(int))
for region, product, qty in sales:
totals[region][product] += qty
print({region: dict(products) for region, products in totals.items()})
# {'north': {'apple': 7, 'pear': 2}, 'south': {'apple': 5}}For totals["north"]["apple"] += 3, Python first evaluates totals["north"], which creates the inner defaultdict(int). It then reads ["apple"] from that inner dictionary, which creates a 0, and adds 3. Each level creates its container on demand.
The last line of the example matters. dict(totals) converts only the outer layer, so the inner values would still be defaultdict objects. The comprehension converts each inner dictionary too.
Choosing a tool
The diagram shows how to pick between these tools.
Pitfalls
Reading a key creates it
With a defaultdict, even a lookup that only reads a value inserts the key. The in operator and get() do not insert anything, so use them when you only want to check.
from collections import defaultdict
d = defaultdict(list)
print(d.get("x")) # None
print("x" in d) # False
_ = d["x"]
print("x" in d) # True
print(dict(d)) # {'x': []}This matters for typos. With a plain dictionary, d["nrth"] raises KeyError. With a defaultdict it quietly adds a bogus "nrth" entry, and your output has an extra key.
Build each inner container separately
The factory style works because every missing key gets a fresh container. The same care applies when you build lists of lists by hand. A comprehension evaluates its element expression once per iteration, so each row is a separate list.
def make_grid(rows, cols, fill=0):
return [[fill] * cols for _ in range(rows)]
grid = make_grid(2, 3)
grid[0][0] = 1
print(grid)
# [[1, 0, 0], [0, 0, 0]]The shortcut [[0] * 3] * 2 repeats one inner list, so both rows are the same object. The shared reference chapter explains that bug in detail. Using a comprehension for each inner container avoids it.
Keep comprehensions readable
A comprehension nested three levels deep is hard to read and harder to debug. If you cannot say what it does in one sentence, split it into named steps or use an ordinary loop.
students = [
{"name": "Ana", "grades": [90, 85]},
{"name": "Ben", "grades": [70, 88, 92]},
]
# One step per level, each easy to check on its own
best = {s["name"]: max(s["grades"]) for s in students}
ranked = sorted(best, key=best.get, reverse=True)
print(ranked)
# ['Ana', 'Ben']Here best has Ana at 90 and Ben at 92, so sorted(..., reverse=True) would put Ben first. The output above is wrong for that data. The correct output is ['Ben', 'Ana']. Printing intermediate results like this is how you catch mistakes in multi-step builds.
Recursive default factories
When the depth is not known ahead of time, a function can return a defaultdict whose factory is that same function. Each new level then creates another level.
from collections import defaultdict
def tree():
return defaultdict(tree)
t = tree()
t["a"]["b"]["c"] = 1
t["a"]["d"] = 2
print(t["a"]["b"]["c"])
# 1
print(sorted(t["a"]))
# ['b', 'd']This is compact, but the "reading creates keys" problem is at its strongest here. Any lookup of a path that does not exist builds it.
Exercises
Exercise
You have pairs = [("x", 1), ("y", 2), ("x", 3), ("y", 4), ("x", 5)]. Write code with defaultdict that produces {'x': [1, 3, 5], 'y': [2, 4]} and prints it as a plain dict.
Show answer
from collections import defaultdict pairs = [("x", 1), ("y", 2), ("x", 3), ("y", 4), ("x", 5)] grouped = defaultdict(list) for key, value in pairs: grouped[key].append(value) print(dict(grouped)) # {'x': [1, 3, 5], 'y': [2, 4]}
Exercise
After running d = defaultdict(int) followed by if d["total"] > 0: pass, does "total" in d return True or False, and why?
Show answer
True. The lookup d["total"] is a missing-key lookup, so the defaultdict calls int(), stores 0 under "total", and returns it. Using d.get("total", 0) would have read the value without inserting the key.
Exercise
Build a 3-by-3 grid of zeros with a comprehension, set the center cell to 5, and explain why [[0] * 3] * 3 would give a different result.
Show answer
grid = [[0] 3 for _ in range(3)]
grid[1][1] = 5
print(grid) # [[0, 0, 0], [0, 5, 0], [0, 0, 0]]
With `[[0] 3] * 3, the outer list holds three references to one inner list. Setting grid[1][1] = 5 would change all three rows, giving [[0, 5, 0], [0, 5, 0], [0, 5, 0]]`.