What Is defaultdict in Python? (With Examples)

What is defaultdict in Python? It’s a dictionary from the collections module that creates a default value the first time you use a missing key, instead of raising KeyError. You choose the default with a function like int or list:

from collections import defaultdict
counts = defaultdict(int)
counts["TX"] += 1      # no KeyError: starts at 0

These examples use order and visit data from US states and cities, and they ran on Python 3.12.5.

We’ll count with defaultdict(int), group with list, collect unique values with set, use lambdas and nesting, and look at the one behavior that catches people out.

defaultdict(int): counting without KeyError

With a normal dict, counts[key] += 1 fails the first time a key appears. defaultdict(int) calls int(), which returns 0, then adds 1:

from collections import defaultdict

states = ["TX", "CA", "TX", "NY", "TX", "CA"]

plain = {}
try:
    for s in states:
        plain[s] += 1
except KeyError as err:
    print("plain dict -> KeyError:", err)

counts = defaultdict(int)          # int() returns 0 for any missing key
for s in states:
    counts[s] += 1
print(counts)
print(dict(counts))

Output:

plain dict -> KeyError: 'TX'
defaultdict(<class 'int'>, {'TX': 3, 'CA': 2, 'NY': 1})
{'TX': 3, 'CA': 2, 'NY': 1}
Command Prompt output of a Python plain dict raising KeyError and a defaultdict(int) counting states
The plain dict failed on the first key; defaultdict counted every state.

A defaultdict is a real dict subclass, so everything else works the same. dict(counts) turns it into a normal dict when you print or save it.

defaultdict(list): grouping values by key

This is the use I reach for most. Each new key starts with its own empty list, so you can append right away:

from collections import defaultdict

orders = [("TX", 59.99), ("CA", 120.00), ("TX", 35.50), ("NY", 89.25), ("CA", 15.75)]

by_state = defaultdict(list)       # list() gives a new empty list per key
for state, amount in orders:
    by_state[state].append(amount)

for state, amounts in by_state.items():
    print(f"{state}: {amounts}  total ${sum(amounts):,.2f}")

Output:

TX: [59.99, 35.5]  total $95.49
CA: [120.0, 15.75]  total $135.75
NY: [89.25]  total $89.25
Command Prompt output of Python defaultdict(list) grouping order amounts by US state with totals
Orders grouped by state in one loop, with no “if key not in dict” check.

Without defaultdict you’d write by_state.setdefault(state, []).append(amount). For merging tabular data, see merge and join in pandas.

Sets, lambdas and nested defaultdicts

Any callable that takes no arguments can be the default factory. set keeps unique values, a lambda gives a custom default, and a defaultdict of defaultdicts builds nested totals:

from collections import defaultdict

visits = [("emily", "Austin"), ("james", "Denver"), ("emily", "Dallas"), ("emily", "Austin")]
cities = defaultdict(set)          # unique values per key
for user, city in visits:
    cities[user].add(city)
print({user: sorted(c) for user, c in cities.items()})   # sorted so the output order is stable

status = defaultdict(lambda: "pending")      # any zero-argument callable works
status["A-1001"] = "shipped"
print(status["A-1001"], status["A-1002"])

sales = defaultdict(lambda: defaultdict(float))   # nested: state -> month -> total
sales["TX"]["Nov"] += 249.50
sales["TX"]["Dec"] += 99.99
sales["FL"]["Nov"] += 75.00
print({state: dict(months) for state, months in sales.items()})

Output:

{'emily': ['Austin', 'Dallas'], 'james': ['Denver']}
shipped pending
{'TX': {'Nov': 249.5, 'Dec': 99.99}, 'FL': {'Nov': 75.0}}
Command Prompt output of Python defaultdict with set for unique cities, a lambda default status and nested defaultdict sales totals
Unique cities per user, a “pending” default, and totals two levels deep.

Lambdas are covered in higher order functions in Python. Note the nested version needs a lambda, because the factory must take no arguments.

Does reading a missing key add it to a defaultdict?

Yes, and it’s the gotcha to remember. d[key] creates the key, but in and .get() don’t:

from collections import defaultdict

stock = defaultdict(int, {"apples": 12})
print("pears" in stock, stock.get("pears"))   # checking doesn't add a key
print(stock["pears"])                         # reading with [] DOES add it
print(dict(stock))

stock.default_factory = None                  # now it behaves like a normal dict
try:
    stock["plums"]
except KeyError as err:
    print("KeyError:", err)

Output:

False None
0
{'apples': 12, 'pears': 0}
KeyError: 'plums'
Command Prompt output showing that a Python defaultdict adds a missing key when read with brackets but not with in or get
Just looking at stock["pears"] added pears with 0. Setting default_factory to None turns that off.

So when you’re only checking, use in or .get(). Otherwise a report loop can quietly fill your dict with zero entries.

defaultdict vs dict.get, setdefault and Counter

ToolBest for
defaultdict(int)Counting while you loop
defaultdict(list)Grouping values by key
CounterCounting a whole iterable at once, plus most_common()
dict.get(key, default)Reading with a fallback, without adding the key
dict.setdefault(key, [])One-off grouping in a normal dict

For renaming keys afterwards, see rename a key in a dictionary.

Other dictionary and collection guides:

Frequently asked questions

What is defaultdict in Python?

A dict subclass from collections that creates a default value for missing keys using a factory function like int or list.

What’s the difference between dict and defaultdict?

A dict raises KeyError for a missing key; a defaultdict creates the key with a default value instead.

Why use defaultdict(list)?

To group items: each new key starts with an empty list, so you can call append right away.

Does checking a key add it to a defaultdict?

key in d and d.get(key) don’t. Reading d[key] does.

How do I convert a defaultdict to a normal dict?

Call dict(d). For nested ones, convert each level, for example with a dict comprehension.

Where is defaultdict documented?

See collections.defaultdict in the Python docs.