Here we will introduce the defaultdict usage in the collections module of Python. The biggest difference from the built-in dictionary class lies in Initialization. let's take a look: defaultdict is mainly used to initialize the value. For the dictionary, the key must be hashable, immutable, and unique data, and the value can be any data type. If the value is a list, dict, or other data type, it must be initialized as null before use. in some cases, the value must be initialized as a special value, such as 0 or ''.
from collections import defaultdictperson_by_age = defaultdict(list)for person in persons: d[person.age].append(person.name)
The usage of defaultdict is the same as that of dict. only a callable object x must be input during initialization. when a non-existent key is accessed, the value is 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 becomes list (), that is, [].
You can also use custom callable objects, such:
d = defaultdict(lambda: 0)d["hello"] += 1 # 1d["a"] # 0
Defaultdict is more efficient and convenient to use than dict. set_default.
The Standard Dictionary includes a method setdefault () to obtain a value. if the value does not exist, a default value is created. When ultdict initializes the container, the caller can specify the default value in advance.
import collectionsdef default_factory(): return 'default value'd = collections.defaultdict(default_factory, foo = 'bar')print 'd:', dprint 'foo =>', d['foo']print 'var =>', d['bar']
This method can be used as long as all keys have the same default value.
The above result is:
d: defaultdict(
, {'foo': 'bar'})foo => barvar => default value