PyDocs

Nav

Data Types

defaultdict

  • defaultdict(default_factory=None, /, **kwargs)
  • defaultdict(default_factory, mapping, /, **kwargs)
  • defaultdict(default_factory, iterable, /, **kwargs)
defaultdict(default_factory=None, /, [...]) --> dict with default factory

The default factory is called without arguments to produce
a new value when a key is not present, in __getitem__ only.
A defaultdict compares equal to a dict with the same items.
All remaining arguments are treated the same as if they were
passed to the dict constructor, including keyword arguments.
Changed in 3.9
  • 3.9: Added merge (|) and update (|=) operators, specified in PEP 584.
Members of defaultdict

_

__missing__
__missing__(key) # Called by __getitem__ for missing key; pseudo-code: if self.default_factory is None: raise KeyError((key,)) self[key] = value = self.default_factory() return value

d

default_factory
Factory for default value called by __missing__().
1 Example
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
...     d[k].append(v)
...
>>> sorted(d.items())
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
from the Python docs
See Also
No see-alsos for collections/defaultdict
0 Notes
No notes for defaultdict