Defaultdict is primarily used for situations where value initialization is required. For a dictionary, the key must be hashable,immutable,unique data, and value can be any data type. If value is a data type such as list,dict, it must be initialized to empty before it is used, and in some cases you need to initialize value 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 and Dict Use the same method, only when the initialization must pass in a callable object X, when access to a nonexistent key, the value automatically set to X (). For example, the first time someone who accesses a certain age D[person.age] becomes a list (), which is [].
Of course, you can also use your own defined callable objects, such as:
D = defaultdict (lambda:0)
d["Hello"] + = 1 # 1
d["A"] # 0
Defaultdict is more efficient than dict.set_default, and more intuitive and convenient to use.
The standard dictionary includes a method SetDefault () to get a value, and a default value if the value does not exist. The Defaultdict initialization container will allow the caller to specify the default value ahead of time.
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 '
You can use this method as long as all keys have the same default value.
The results above are:
D:defaultdict (<function default_factory at 0x0201fab0>, {' foo ': ' Bar '})
foo => bar
var => default V Alue