A subclass of Python's dict class that allows to specify a default factory to use for missing keys.
This tag would be applicable to Python questions related with the instantiation, filling and subclassing of the collections.defaultdict
class.
defaultdict
is a subclass of the built-in dict class. It overrides one method and adds one writable instance variable. The remaining functionality is the same as for the dict class.
collections.defaultdict([default_factory[, ...]])
The first argument provides the initial value for the default_factory attribute; it defaults to None
. Commonly used default_factories are int
, list
or dict
.
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
... d[k].append(v)
...
>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
this is equivalent to:
>>> d = dict()
>>> for k, v in s:
... d.setdefault(k, []).append(v)
...