defaultdict is mainly used when value needs to be initialized. For a dictionary, the key must be hashable, immutable, and unique data, and the value can be any data type. If value is a data type such as list, dict, etc., it must be initialized to empty before use. In some cases, value needs to be initialized to a special value, such as 0 or ''.
from collections import defaultdict person_by_age = defaultdict(list) for person in persons: d[person.age].append(person.name)
defaultdict is used in the same way as dict, except that a callable object x must be passed in during initialization. When a key that does not exist yet is accessed, the value will be automatically set to x(). For example, in the above example, when a person of a certain age d[person.age] is accessed for the first time, it will become list(), that is, [].
Of course, you can also use your own defined callable object, such as:
d = defaultdict(lambda: 0) d["hello"] += 1 # 1 d["a"] # 0
defaultdict is more efficient than dict.set_default, and is more intuitive and convenient to use.
The standard dictionary includes a method setdefault() to get a value and create a default value if the value does not exist. defaultdict initializes the container to allow the caller to specify the default value in advance.
import collections def default_factory(): return 'default value' d = collections.defaultdict(default_factory, foo = 'bar') print 'd:', d print 'foo =>', d['foo'] print 'var =>', d['bar']
This method can be used as long as all keys have the same default value.
The result above is:
d: defaultdict(<function default_factory at 0x0201FAB0>, {'foo': 'bar'}) foo => bar var => default value