Sub topic 4
Grouping and accumulating with defaultdict
This chapter assumes you can write loops and functions, use dict and list (key lookup, append), and know why only hashable objects can be dict keys. It also assumes you can import names from the standard library.
The problem defaultdict solves
Grouping items in a plain dict forces you to handle the first appearance of every key:
words = ["apple", "avocado", "banana", "blueberry", "cherry"]
by_letter = {}
for word in words:
if word[0] not in by_letter:
by_letter[word[0]] = []
by_letter[word[0]].append(word)
print(by_letter)
# {'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}The if check exists only to avoid a KeyError. A defaultdict removes it. It is a dict subclass from the collections module that builds a starting value whenever you look up a key it doesn't have.
Grouping with defaultdict(list)
You give defaultdict a factory: a callable that takes no arguments and returns the starting value.
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']}When by_letter["a"] is read for the first time, defaultdict calls list(). It stores the empty list under "a" and returns it, so .append(word) works immediately. Later lookups find the stored list.
Accumulating with defaultdict(int)
int() returns 0, so defaultdict(int) works as a running total. Each key starts at zero and += adds to it:
from collections import defaultdict
sales = [("fruit", 3), ("veg", 2), ("fruit", 4)]
totals = defaultdict(int)
for category, amount in sales:
totals[category] += amount
print(dict(totals)) # {'fruit': 7, 'veg': 2}The statement totals[category] += amount first reads totals[category], which creates the 0 if needed. It then adds and stores the result. For plain counting of items, Counter (previous chapters) is usually clearer. defaultdict(int) fits best when you add amounts other than 1.
Choosing a factory
Any zero-argument callable can be a factory. These are the common ones:
| Factory | Starting value | Typical use |
|---|---|---|
| `list` | `[]` | Group items, keeping order and duplicates |
| `set` | `set()` | Group items, keeping each one once |
| `int` | `0` | Running totals and counts |
| `float` | `0.0` | Running sums of decimal amounts |
| `dict` | `{}` | One level of nesting |
| `lambda: "n/a"` | `"n/a"` | Any custom constant |
Use set when duplicates would be wrong. This example records which values belong to each key:
from collections import defaultdict
pairs = [("a", 1), ("a", 1), ("b", 2), ("a", 3)]
seen = defaultdict(set)
for key, value in pairs:
seen[key].add(value)
print(dict(seen)) # {'a': {1, 3}, 'b': {2}}For a custom default, wrap it in a lambda or a named function:
from collections import defaultdict
status = defaultdict(lambda: "unknown")
status["job1"] = "done"
print(status["job1"]) # done
print(status["job2"]) # unknownNested defaultdicts
A factory can itself create a defaultdict. Here, each outer key gets its own inner counter:
from collections import defaultdict
visits = defaultdict(lambda: defaultdict(int))
visits["mon"]["home"] += 1
visits["mon"]["home"] += 1
visits["mon"]["about"] += 1
print({day: dict(pages) for day, pages in visits.items()})
# {'mon': {'home': 2, 'about': 1}}The lambda is required. Writing defaultdict(defaultdict(int)) fails, because the argument must be a callable and not an existing defaultdict object.
Common errors
- Passing a value instead of a factory.
defaultdict([])raisesTypeError: first argument must be callable or None. Passlist, with no parentheses. - Expecting reads to be free. Indexing a missing key creates it. Checking
totals["typo"]adds"typo"to the dictionary. Useinor.get(key)when you only want to look. The next chapter covers this in detail. - Using a mutable shared default.
defaultdict(lambda: shared_list)returns the same list for every key. Create a fresh object inside the factory, aslistdoes. - Printing for display. A
defaultdictprints with its factory (defaultdict(<class 'list'>, {...})). Wrap it indict(...)for clean output or JSON. - Assuming the factory affects
.get().d.get(key)returnsNonefor missing keys and never calls the factory.
Choosing between a plain dict and defaultdict
A plain dict with setdefault or get is fine for a one-off. For example, d.setdefault(k, []).append(v) builds a new empty list on every call, even when the key exists. defaultdict(list) creates the list only when the key is missing, and the loop body reads more clearly. If you group or total in more than one place, defaultdict removes repeated boilerplate.
Exercise
Given orders = [("ann", 5), ("bob", 3), ("ann", 2)], write code that uses a defaultdict to compute each person's total, then print it as a plain dict. What does it print?
Show answer
from collections import defaultdict orders = [("ann", 5), ("bob", 3), ("ann", 2)] totals = defaultdict(int) for name, amount in orders: totals[name] += amount print(dict(totals)) It prints {'ann': 7, 'bob': 3}. The int factory gives each new name a starting total of 0.
Exercise
Why does defaultdict(list()) fail, and what is the correct call?
Show answer
list() produces an empty list, which is not callable, so defaultdict raises TypeError. The factory must be the callable itself, so write defaultdict(list).