Sub topic 4
Grouping and accumulating with defaultdict
This chapter assumes you can write loops and functions in Python and use dict and list comfortably, including key lookup, append, and KeyError. It also assumes you know that dict keys must be hashable, and that you can import names from the standard library. Counter and deque are covered in other chapters. Here the focus is defaultdict, a dictionary that creates a starting value for a key the first time you read it.
The problem: checking whether a key exists
Many tasks need a dictionary whose values are built up one item at a time. Examples are grouping words by first letter, summing amounts per region, and collecting the set of tags per user. With a plain dict, every update has to handle the case where the key is not there yet.
words = ["apple", "avocado", "banana", "blueberry", "cherry"]
groups = {}
for word in words:
key = word[0]
if key not in groups:
groups[key] = []
groups[key].append(word)
print(groups)
# {'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}The two lines that check and create the list are not about the task. They are bookkeeping, and you have to repeat them in every loop of this kind.
There are two common ways to shorten this with a plain dict:
words = ["apple", "avocado", "banana", "blueberry", "cherry"]
# Option 1: setdefault
groups = {}
for word in words:
groups.setdefault(word[0], []).append(word)
# Option 2: try/except
groups2 = {}
for word in words:
try:
groups2[word[0]].append(word)
except KeyError:
groups2[word[0]] = [word]
print(groups == groups2) # Truesetdefault works, but it builds a new empty list on every call, even when the key already exists and the new list is thrown away. The try/except version is correct but long. defaultdict moves the "create it if missing" rule into the dictionary itself.
Creating a defaultdict
defaultdict lives in the collections module. It is a subclass of dict, so it supports everything a dict does: iteration, len, in, items(), del, and so on. The one difference is what happens when you index a key that is not there.
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']}The first argument, list, is the default factory. It is a callable that takes no arguments and returns a new value. When you read by_letter["a"] and "a" is missing, the dictionary calls list(), stores the empty list under "a", and returns it. Then .append(word) works on that list as usual.
The general form is:
defaultdict(default_factory=None, *args, **kwargs)Everything after the first argument is passed to the ordinary dict constructor. You can seed a defaultdict with starting data in the same ways you would a dict:
from collections import defaultdict
d = defaultdict(int, a=1, b=2)
print(d) # defaultdict(<class 'int'>, {'a': 1, 'b': 2})
print(d.default_factory) # <class 'int'>
e = defaultdict(list, {"x": [1, 2]})
e["x"].append(3)
e["y"].append(10)
print(dict(e)) # {'x': [1, 2, 3], 'y': [10]}The factory is stored in the attribute default_factory. You can read it and reassign it at any time.
How a lookup behaves
The diagram shows what happens on d[key]. A key that is already present behaves as in any dict. Only a missing key reaches the factory.
Two points follow from this path:
- Reading a missing key through
d[key]changes the dictionary. The key is now there. The next chapter covers this in detail, including howget()andindiffer. - The factory is called with no arguments. It never receives the key. If you need a default that depends on the key, you need a different approach, such as subclassing
dictand defining__missing__.
Grouping with list
defaultdict(list) is the most common form. Each key maps to a list of the items that belong to it. The pattern has three steps: pick a key for each item, index with that key, and append.
Grouping words by length:
from collections import defaultdict
words = ["pear", "fig", "plum", "kiwi", "lime", "date", "apple"]
by_length = defaultdict(list)
for word in words:
by_length[len(word)].append(word)
print(dict(by_length))
# {4: ['pear', 'plum', 'kiwi', 'lime', 'date'], 3: ['fig'], 5: ['apple']}Any hashable value can be a key, so integers, strings, and tuples all work here. The items stay in the order they were seen, because append adds to the end of each list. The keys also keep the order in which they first appeared.
Grouping records from a list of pairs is the same pattern:
from collections import defaultdict
orders = [("alice", "tea"), ("bob", "coffee"), ("alice", "cake"), ("bob", "tea")]
items_by_customer = defaultdict(list)
for customer, item in orders:
items_by_customer[customer].append(item)
print(dict(items_by_customer))
# {'alice': ['tea', 'cake'], 'bob': ['coffee', 'tea']}You can also invert a mapping. Suppose several keys share the same value, and you want to go from each value back to all of its keys:
from collections import defaultdict
owner_of = {"report.txt": "ann", "notes.md": "raj", "plan.txt": "ann"}
files_of = defaultdict(list)
for filename, owner in owner_of.items():
files_of[owner].append(filename)
print(dict(files_of))
# {'ann': ['report.txt', 'plan.txt'], 'raj': ['notes.md']}itertools.groupby also groups items, but it only groups neighbours. It needs input sorted by the same key, or equal keys that are apart end up in separate groups. A defaultdict has no such requirement, and it makes a single pass over unsorted data. The cost is that all the data is held in memory at once.
Accumulating with int and float
When the value for each key is a running total, use int or float as the factory. int() returns 0 and float() returns 0.0, which are the right starting points for addition.
from collections import defaultdict
sales = [("north", 120), ("south", 80), ("north", 45), ("east", 60), ("south", 20)]
totals = defaultdict(int)
for region, amount in sales:
totals[region] += amount
print(dict(totals)) # {'north': 165, 'south': 100, 'east': 60}The line totals[region] += amount expands to totals[region] = totals[region] + amount. The read on the right side is what triggers the factory for a new region, so it starts at 0. With a plain dict this line would raise KeyError.
Counting is the same idea with += 1:
from collections import defaultdict
letters = defaultdict(int)
for ch in "mississippi":
letters[ch] += 1
print(dict(letters)) # {'m': 1, 'i': 4, 's': 4, 'p': 2}This works, but Counter does it in one call and adds helpers such as most_common. Use defaultdict(int) for counting when you want to keep the code simple and have no need for those helpers. Use it for sums, where Counter is not a natural fit, when the amounts are not simple increments.
Use float when the totals are not whole numbers, for example prices:
from collections import defaultdict
prices = [("tea", 2.5), ("cake", 4.0), ("tea", 2.5)]
spent = defaultdict(float)
for item, price in prices:
spent[item] += price
print(dict(spent)) # {'tea': 5.0, 'cake': 4.0}Other factories: set, dict, str, and your own
Any zero-argument callable can be the factory. The built-in types are the common choices, and each one gives a different shape of value.
| Factory | Default value | Typical use |
|---|---|---|
| `list` | `[]` | Group items, keeping order and duplicates |
| `set` | `set()` | Group items, keeping each one once |
| `int` | `0` | Counts and integer sums |
| `float` | `0.0` | Numeric totals |
| `str` | `""` | Build text by concatenation |
| `dict` | `{}` | Two-level mappings |
defaultdict(set) removes duplicates automatically, because adding an item that is already in the set changes nothing:
from collections import defaultdict
pairs = [("fruit", "apple"), ("veg", "kale"), ("fruit", "apple"), ("fruit", "pear")]
index = defaultdict(set)
for kind, name in pairs:
index[kind].add(name)
print({kind: sorted(names) for kind, names in index.items()})
# {'fruit': ['apple', 'pear'], 'veg': ['kale']}Sets have no defined order, so the example sorts them before printing. A set also requires that its items are hashable.
For a default that is not a built-in type's empty value, use a lambda or a named function:
from collections import defaultdict
scores = defaultdict(lambda: 100)
scores["ann"] -= 10
print(scores["ann"], scores["bob"]) # 90 100Here every new player starts with 100 points. Note that scores["bob"] in the print call also inserted "bob" with the value 100.
Nested defaultdicts
A factory can itself create a defaultdict. This gives a two-level structure where neither level needs a missing-key check:
from collections import defaultdict
events = [("alice", "login"), ("alice", "click"), ("bob", "login"), ("alice", "click")]
counts = defaultdict(lambda: defaultdict(int))
for user, action in events:
counts[user][action] += 1
print({user: dict(actions) for user, actions in counts.items()})
# {'alice': {'login': 1, 'click': 2}, 'bob': {'login': 1}}The outer factory is a lambda because defaultdict(int) must be created fresh for each user, and the factory has to be a callable that returns it. Writing defaultdict(defaultdict(int)) would raise a TypeError, because the first argument would be a defaultdict instance, not a callable.
For a structure of unknown depth, a function can refer to itself:
from collections import defaultdict
def tree():
return defaultdict(tree)
root = tree()
root["config"]["db"]["port"] = 5432
root["config"]["db"]["host"] = "localhost"
print(root["config"]["db"]["port"]) # 5432
print(list(root["config"]["db"])) # ['port', 'host']This is convenient for building nested data in one expression. Be careful with it: because every lookup creates a node, a mistyped key quietly adds a new empty branch instead of failing. For fixed, known shapes, a dataclass or ordinary dict is safer.
Common errors
Passing a value instead of a callable. The factory is called, so it must be callable.
from collections import defaultdict
try:
defaultdict(0)
except TypeError as error:
print(error) # first argument must be callable or NoneWrite defaultdict(int) to get a default of 0. Write defaultdict(lambda: 0) if you prefer the explicit form. The same applies to defaultdict([]), which also fails. Use defaultdict(list).
Using a factory of None. A defaultdict with no factory, or with None, behaves like a plain dict and raises KeyError on a missing key.
from collections import defaultdict
d = defaultdict()
print(d.default_factory) # None
try:
d["x"]
except KeyError as error:
print("KeyError:", error) # KeyError: 'x'Setting d.default_factory = list later turns the default behaviour on.
Sharing one mutable object. The factory runs for every new key, so it must return a new object each time. A factory that returns the same list gives every key the same list.
from collections import defaultdict
shared = []
d = defaultdict(lambda: shared)
d["a"].append(1)
d["b"].append(2)
print(d["a"]) # [1, 2]
print(d["a"] is d["b"]) # TrueExpecting in or len to trigger the factory. Only indexing with [] calls the factory. The test "y" in d and the call len(d) never create a key. The reverse also holds: any read through d[key], even one whose result you ignore, adds the key. Reading a key to check it, such as if d["y"]:, grows the dictionary. The next chapter explains this and shows how to check without inserting.
Lambdas and pickling. A defaultdict whose factory is a lambda cannot be pickled, because pickle cannot store lambdas by name. If you need to pickle or share the structure between processes, use a named module-level function or a built-in type such as list.
Choosing between defaultdict and the alternatives
A short comparison for the grouping and accumulating tasks in this chapter:
| Approach | Strength | Weakness |
|---|---|---|
| `if key not in d` | Explicit, no imports | Repeated bookkeeping in every loop |
| `d.setdefault(k, [])` | One line, plain dict | Builds a throwaway object on each call |
| `try/except KeyError` | Fast when keys usually exist | Verbose |
| `defaultdict(factory)` | Shortest, factory runs only when needed | Reads insert keys; lambda factories block pickling |
| `Counter` | Counting with extra helpers | Only for numeric counts |
Use defaultdict when every key in the result should start from the same kind of value, and you only ever add to it. If you only want defaults when reading but do not want the dictionary to grow, use d.get(key, default) on a plain dict instead.
Summary of the pattern
- Choose the shape of each value:
listto keep items,setto keep unique items,intorfloatto total numbers. - Create
defaultdict(that_factory). - In the loop, compute the key and update
d[key]directly, with.append,.add, or+=. - When you are done, convert with
dict(d)if the result will leave your function.
Exercise
What does this code print, and why? from collections import defaultdict d = defaultdict(list) d["a"].append(1) print(len(d)) print("b" in d) d["b"] print("b" in d) print(len(d))
Show answer
It prints 1, False, True, and 2. The append on "a" creates that key, so len is 1. The test "b" in d never calls the factory, so it is False. The bare expression d["b"] is an index lookup on a missing key, so the dictionary calls list(), stores [] under "b", and discards the result. After that "b" in d is True and len(d) is 2.
Exercise
Write a function totalbycategory(rows) that takes a list of (category, amount) tuples and returns a plain dict of the total amount per category. Use defaultdict. For example, totalbycategory([("a", 2), ("b", 5), ("a", 3)]) should return {"a": 5, "b": 5}.
Show answer
from collections import defaultdict def totalbycategory(rows): totals = defaultdict(int) for category, amount in rows: totals[category] += amount return dict(totals) The factory int returns 0 for each new category, so the += works on the first sight of a key. Returning dict(totals) hands back a plain dict, so callers cannot create keys by accident.
Exercise
A teammate writes groups = defaultdict(lambda: shared) where shared = [] was created earlier, and then groups["x"].append(1) and groups["y"].append(2). What is groups["x"], and how would you fix the code so each key gets its own list?
Show answer
groups["x"] is [1, 2], because the lambda returns the same list object for every key. Fix it by letting the factory create a new list each time: groups = defaultdict(list), or groups = defaultdict(lambda: []).