CKTIS / Python
collections.defaultdict
Creates a missing value by calling the factory when a key is accessed by subscription.
Version: Python 3.14; repository image, production runtime not attested
Syntax
collections.defaultdict(list)Creates a missing value by calling the factory when a key is accessed by subscription.
The ordinary dictionary lookup method with a default bypasses the factory and leaves the mapping unchanged.
A missing subscription invokes default_factory without arguments, saves its result under the requested key and returns it. With None as the factory that subscription raises KeyError. The initial get in the sample leaves groups empty. Indexing creates one list, so the following append stores 8 in that group. The missing-key hook __missing__ handles subscription and is bypassed by get. If the factory raises ValueError, the exception propagates and the requested key is not inserted.
from collections import defaultdict
d = defaultdict(list)
assert d.get("x") is None and "x" not in d
assert d["x"] is d["x"] and d["x"] is not d["y"]
d.default_factory = None
try:
d["z"]
except KeyError:
assert "z" not in d
else:
raise AssertionError
def fail():
raise ValueError("no group")
d = defaultdict(fail)
assert d.get("new") is None
try:
d["new"]
except ValueError:
assert "new" not in d
else:
raise AssertionError
Examples
import collections
groups = collections.defaultdict(list)
print(groups.get("a"), len(groups))
groups["a"].append(8)
print(dict(groups))
Result
None 0
{'a': [8]}A missing subscription invokes default_factory without arguments, saves its result under the requested key and returns it. With None as the factory that subscription raises KeyError. The initial get in the sample leaves groups empty. Indexing creates one list, so the following append stores 8 in that group. The missing-key hook `__missing__` handles subscription and is bypassed by get. If the factory raises ValueError, the exception propagates and the requested key is not inserted.