collections.defaultdict

RoadmapsPython

Overview

`collections.defaultdict(factory)` is a dict that auto-creates a value the first time you touch a missing key, using the zero-argument `factory` you pass. It removes the 'check if key exists, else initialize' boilerplate. from collections import defaultdict groups = defaultdict(list) # missing key -> [] groups['a'].append(1) # no KeyError; makes [] then appends counts = defaultdict(int) # missing key -> 0 counts['x'] += 1 # 0 + 1 The factory is any zero-arg callable: `list`→`[]`, `int`→`0`, `set`→`set()`, `dict`→`{}`, or your own `lambda: ...`. Key subtlety: merely *accessing* a missing key (`d[k]`) inserts the default and grows the dict — a side effect a plain dict doesn't have.

Grouping and counting are everywhere — bucketing records by a field, tallying frequencies, building adjacency lists for graphs. `defaultdict` makes these one-liners and shows up constantly in interview solutions.

Where used: Grouping records by a key, Frequency counting / tallies, Graph adjacency lists

Why learn this

Code walkthrough

from collections import defaultdict

counts = defaultdict(int)
for ch in 'mississippi':
    counts[ch] += 1

print(dict(counts))

Focus: counts[ch] += 1 (missing key starts at 0, so += works with no setup)

Common mistakes

Glossary

factory function
A zero-argument callable that produces the default value for a missing key. Example: `defaultdict(list)` calls `list()` to make `[]`.

Recall questions

Understanding checks

What are the two printed lines?

[] then 1

Accessing missing key 'x' triggers the `list` factory, so it prints `[]` — and that access also inserts 'x' into the dict, so its length is now 1 (the read had a side effect).

Why does this raise an error?

`int()` is the value `0`, not a callable; defaultdict needs a factory function, so pass `int` (without parentheses).

defaultdict calls the factory for each missing key. `int` is callable and returns 0; `int()` is already 0 and can't be called, causing a TypeError on the first missing-key access.

Practice tasks

Group words by first letter

Given the list of words, build a dict mapping each first letter to the list of words starting with it, using defaultdict so you never check for missing keys.

Continue learning

Previous: Dictionaries: operations and use cases

Next: collections.Counter

Return to Python Roadmap