Sub topic 7
Building nested structures with comprehensions and defaultdict
This chapter assumes you can index lists, look up dictionary keys, write for loops and functions, and read nested data with chained indexing. Here you build nested data instead of typing it out by hand.
Comprehensions that build nested data
A comprehension is an expression that builds a list or dictionary from a loop. Put one inside another to create nested data.
grid = [[0 for _ in range(3)] for _ in range(2)]
print(grid) # [[0, 0, 0], [0, 0, 0]]
names = ["Ana", "Ben"]
scores = {name: [] for name in names}
print(scores) # {'Ana': [], 'Ben': []}
table = {n: {"square": n * n, "cube": n ** 3} for n in range(1, 4)}
print(table)
# {1: {'square': 1, 'cube': 1}, 2: {'square': 4, 'cube': 8}, 3: {'square': 9, 'cube': 27}}The inner expression runs once for every outer item. Each row, list, or inner dictionary is therefore a separate object. This matters for the bug in the next chapter, where [[0] * 3] * 2 repeats a single inner list instead.
Grouping with setdefault()
Grouping is the most common building task. You have a flat sequence and want a dictionary of lists. The setdefault(key, default) method returns the existing value for key. If the key is missing, it stores default and returns that.
pairs = [("fruit", "apple"), ("veg", "kale"), ("fruit", "pear")]
groups = {}
for category, item in pairs:
groups.setdefault(category, []).append(item)
print(groups) # {'fruit': ['apple', 'pear'], 'veg': ['kale']}This replaces the longer if key not in groups: groups[key] = [] check. One cost is that [] is created on every call, even when the key already exists and the new list is thrown away.
Grouping with defaultdict
A defaultdict takes a factory, which is a function that creates a default value. When you use a missing key, it calls the factory and stores the result.
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']}Use defaultdict(int) for counters, defaultdict(list) for groups, and defaultdict(set) for groups without duplicates.
Two levels deep
To nest a defaultdict inside another, the outer factory must create the inner one. A lambda does this.
from collections import defaultdict
sales = [
("north", "apples", 3),
("north", "pears", 2),
("south", "apples", 5),
("north", "apples", 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': {'apples': 7, 'pears': 2}, 'south': {'apples': 5}}The line totals[region][product] += qty creates the region, then the product, then adds. No existence checks are needed at either level.
Common errors
The most frequent mistake is forgetting that a read can also create a key. Looking up a missing key in a defaultdict adds it.
from collections import defaultdict
counts = defaultdict(int)
print(counts["missing"]) # 0
print("missing" in counts) # True
print(dict(counts)) # {'missing': 0}Other points to watch:
- Wrong factory.
defaultdict([])raises aTypeError, because the factory must be callable. Passlist, not[]. - Leaking the type. A
defaultdictkeeps creating keys wherever it is passed. Convert it withdict(...)before returning it from a function. Nested levels need their own conversion, as the dictionary comprehension above shows. - Hidden typos. With a plain dictionary, a misspelled key raises
KeyError. With adefaultdict, it silently creates a new entry.
Choosing a tool
| Task | Good fit |
|---|---|
| Fixed-shape grid or table | Nested list comprehension |
| One key per known item, empty containers | Dictionary comprehension |
| Grouping or counting a stream of items | `defaultdict` |
| One-off grouping in a small script | `setdefault()` |
Exercise
Given rows = [("math", "Ana", 90), ("math", "Ben", 70), ("art", "Ana", 85)], build a dictionary shaped like {subject: {student: score}} using defaultdict. What do you write?
Show answer
Use a defaultdict whose factory creates a plain dict: from collections import defaultdict result = defaultdict(dict) for subject, student, score in rows: result[subject][student] = score print(dict(result)) # {'math': {'Ana': 90, 'Ben': 70}, 'art': {'Ana': 85}} Each subject gets an empty dict on first use, and then the student's score is assigned into it. Plain assignment needs no inner defaultdict. An inner defaultdict(int) is only needed when you add to values that may not exist yet.