# Python Defaultdict: a dict that fills missing keys

Published: 2026-11-30

Rights: original
Source: https://kairos-2z6s.onrender.com/res/python-defaultdict-full-en
`collections.defaultdict(factory)` calls `factory()` for a missing key and stores the result, so `d[key].append(x)` works with `factory=list`.

Each command below is the exact command that was run and each output block is copied from the recorded log. Test ids, log hashes and exit statuses are in the evidence table.

(Test: 3 tests were run, TE-84-A, TE-84-B and TE-84-C. The expected non-zero exit is TE-84-C (exit status 1). Every row has a recorded log, and the exit statuses and log hashes are in the evidence table.)

### TE-84-A: defaultdict(list) groups items, and reading a missing key adds it

Setup for this run, inside a throwaway directory (`mktemp -d`):

```bash
cat > s.py <<'EOS'
from collections import defaultdict
d = defaultdict(list)
for w in ['ant', 'bee', 'ape']:
    d[w[0]].append(w)
print(dict(d))
print(len(d))
d['z']
print(len(d))
EOS
```

Command:

```bash
python3 s.py
```

Recorded output:

```
{'a': ['ant', 'ape'], 'b': ['bee']}
2
3
```

Exit status: 0. The output matches the expected text written before the run.

### TE-84-B: defaultdict(int) starts a missing key at 0, and default_factory shows the factory

Setup for this run, inside a throwaway directory (`mktemp -d`):

```bash
cat > s.py <<'EOS'
from collections import defaultdict
d = defaultdict(int)
for ch in 'aab':
    d[ch] += 1
print(dict(d))
print(d.default_factory)
EOS
```

Command:

```bash
python3 s.py
```

Recorded output:

```
{'a': 2, 'b': 1}
<class 'int'>
```

Exit status: 0. This status and the output match what was written before the run.

### TE-84-C: expected non-zero exit: a defaultdict created without a factory raises KeyError for a missing key

Setup for this run, inside a throwaway directory (`mktemp -d`):

```bash
cat > s.py <<'EOS'
from collections import defaultdict
d = defaultdict()
d['x']
EOS
```

Command:

```bash
python3 s.py
```

Recorded output: none, standard output was empty.

Standard error from the same run:

```
Traceback (most recent call last):
  File "/tmp/b22-pbekeipe/work/s.py", line 3, in <module>
    d['x']
KeyError: 'x'
```

Exit status: 1. This status and the output match what was written before the run. The path in the traceback line is a temporary folder and differs on each machine and each run.

TE-84-B: with int as the factory, each new key started at 0, so a is 2 and b is 1, and default_factory prints <class 'int'>. TE-84-C: a defaultdict without a factory raised an error for the missing key x. The program ended with exit status 1 and the last line of standard error is KeyError: 'x'.

## Limits

TE-84-A runs the `list` factory and TE-84-B runs the `int` factory. Reading a missing key adds it, which the run shows.

## Source

- https://docs.python.org/3/library/collections.html#collections.defaultdict

## Evidence table

| Test | What it checks | Exit | Verdict | Log sha256 (first 12) |
|---|---|---|---|---|
| `TE-84-A` | defaultdict(list) groups items, and reading a missing key adds it | 0 | PASS | `6d819a1514b4` |
| `TE-84-B` | defaultdict(int) starts a missing key at 0, and default_factory shows the factory | 0 | PASS | `21e80b83def3` |
| `TE-84-C` | expected non-zero exit: a defaultdict created without a factory raises KeyError for a missing key | 1 | PASS | `7dc74a9822fd` |

Recorded on: bash 5.1.16(1)-release; git version 2.34.1; Python 3.10.12. Locale C.UTF-8, TZ=UTC.
Every row has a recorded log holding the setup commands, the command, stdout, stderr and exit status. The first 12 characters of the log's sha256 are in the table.

## Related guides
- [Python Dataclasses: a class that stores values](https://kairos-2z6s.onrender.com/res/python-dataclasses-full-en)
- [Python Counter: count items](https://kairos-2z6s.onrender.com/res/python-counter-full-en)
- [Python dictionaries: lookup, default values and the KeyError](https://kairos-2z6s.onrender.com/res/python-dict-basics-full-en)
- [Python Default Arguments: evaluated once](https://kairos-2z6s.onrender.com/res/python-default-arguments-full-en)
- [Python dates: parse and compare](https://kairos-2z6s.onrender.com/res/python-dates-full-en)
