Python Glossary Русский

all Python 3collectionsterm

collections.defaultdict

defaultdict

A dictionary with a factory for default values. When a missing key is accessed, the factory creates the value.

Syntax

collections.defaultdict(default_factory, ...)

The factory fires on a read of d[key], so merely touching a missing key silently inserts an entry and grows the dict; use in or .get() when you just want to check, since neither triggers __missing__. Also, default_factory must be a zero-argument callable, not a ready value: write defaultdict(list) or defaultdict(int), never defaultdict([]) or defaultdict(0).

Examples

from collections import defaultdict
d = defaultdict(list)
d['fruits'].append('apple')
d['fruits'].append('banana')
print(d)  # → defaultdict(<class 'list'>, {'fruits': ['apple', 'banana']})
from collections import defaultdict
counter = defaultdict(int)
for c in 'hello':
    counter[c] += 1
print(dict(counter))  # → {'h': 1, 'e': 1, 'l': 2, 'o': 1}
from collections import defaultdict
by_letter = defaultdict(list)
for w in ['apple', 'ant', 'bat', 'ball', 'cat']:
    by_letter[w[0]].append(w)
print(dict(by_letter))  # → {'a': ['apple', 'ant'], 'b': ['bat', 'ball'], 'c': ['cat']}
from collections import defaultdict
d2 = defaultdict(lambda: 'unknown')
d2['key1'] = 'value'
print(d2['key1'])  # → value
print(d2['missing'])  # → unknown — и ключ 'missing' теперь в словаре
print(len(d2))  # → 2
from collections import defaultdict
grid = defaultdict(lambda: defaultdict(int))
grid['row1']['col1'] += 1
print(grid['row1']['col1'])  # → 1

See also

Open in the full glossarydocs.python.orgReport an inaccuracy