How it works
defaultdict is a dict subclass with a default factory. A missing subscription such as groups[key] calls the factory without arguments, inserts its result and returns it.
Pass the callable list, not list(). Each missing key then receives its own list. get does not invoke the factory, so it can inspect absence without adding a key.
Choices and common mistakes
A read through subscription can change the dictionary by adding a missing entry. Use membership or get when that side effect is unwanted.
Use Counter for straightforward frequency counting; use defaultdict when you need general grouping or a different default value.
Try it yourself
Group filenames by extension. Check both a missing subscription and get on a missing extension, and compare the keys afterwards.
Syntax
from collections import defaultdict
groups = defaultdict(list)
groups[key].append(value)Examples
Group records
Collect names into a list for each team.
from collections import defaultdict
teams = defaultdict(list)
for team, name in [("blue", "John"), ("red", "James"), ("blue", "Sam")]:
teams[team].append(name)
print(dict(teams))- The first subscription for each team creates an empty list. append adds the current name to that team’s list.
- Later blue entries reuse its existing list. Converting to dict makes the printed result focus on the collected records.
- This is useful for grouping query results for a report, while keeping each group in encounter order.
- Expected output: {'blue': ['John', 'Sam'], 'red': ['James']}
Inspect without inserting
Compare get with a missing subscription.
from collections import defaultdict
counts = defaultdict(int)
print(counts.get("new"))
print("new" in counts)
print(counts["new"])
print("new" in counts)- get returns its ordinary default None and leaves the dictionary unchanged.
- Subscription calls int(), which returns zero, and stores it under new. The final membership test reveals the insertion.
- Use get when checking optional state should not create a record.
- Expected output: None False 0 True
Create distinct lists
Verify that missing keys do not share the same container.
from collections import defaultdict
groups = defaultdict(list)
groups["a"].append(1)
groups["b"].append(2)
print(groups["a"])
print(groups["b"])
print(groups["a"] is groups["b"])- Each missing key triggers a separate list() call. Appending to one group therefore leaves the other group unchanged.
- The identity test is False because these are different list objects, not just different names for one list.
- Avoid a factory that returns one shared mutable object unless sharing is explicitly intended.
- Expected output: [1] [2] False
Best practices
- A read through subscription can change the dictionary by adding a missing entry. Use membership or get when that side effect is unwanted.
- Use Counter for straightforward frequency counting; use defaultdict when you need general grouping or a different default value.
Runtime & versions
Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Python language reference