Python Reference ยท Standard Library: Data Structures and Functional Tools
collections.defaultdict
Reference for Python collections.defaultdict: dicts that create missing values with a factory, grouping, nested defaults, __missing__ and the lookup side effect.
A defaultdict is a dict that knows how to create a value when you look up a key that is not there. You pass a zero-argument callable (the default factory) such as list, int or set; when d[key] fails, the factory is called, its result is stored under key, and that value is returned.
That makes grouping and counting loops much shorter, because you no longer test if key not in d before every update.
from collections import defaultdict groups = defaultdict(list) groups["fruit"].append("apple")
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
defaultdict(default_factory=None, /, *args, **kwargs)
| Name | Description |
|---|---|
default_factory |
A callable taking no arguments, or None. Called when a key is missing; stored in the attribute of the same name. |
*args, **kwargs |
Anything the dict constructor accepts (a mapping, pairs, keyword arguments). |
Return value: a new defaultdict, which supports every dict method.
Raises: TypeError if the first argument is neither callable nor None. A missing key raises KeyError when default_factory is None.
Usage notes
- Only
d[key]triggers the factory.get(),in, andsetdefault()do not call it, sod.get(key)still returnsNonefor a missing key. - Reading creates the key. Even a lookup you only meant to inspect inserts a default entry. Use
key in dord.get(key)for read-only checks. - The factory takes no arguments. To start from a specific value use a lambda:
defaultdict(lambda: 100). - Mutable defaults are safe here. Each missing key gets its own fresh
list()orset(), unlike a shared default argument in a function. - Works through
__missing__.dict.__getitem__calls the__missing__()method when a key is absent;defaultdictimplements it. You can use the same hook in your owndictsubclass. - Printing shows the factory:
defaultdict(<class 'list'>, {...}). Convert withdict(d)for a plain display, or if you must stop it from creating keys later. - Not the same as
Counter. For plain counting,Counteraddsmost_common()and arithmetic; for grouping,defaultdict(list)is the usual tool. - Pickling and JSON. A
defaultdictwith a lambda factory cannot be pickled;json.dumpstreats it as a normal dict.