Example of using the Python standard library defaultdict Module
In the Python standard library, collections performs a lot of expansion operations on the data structure of the set type. These operations will bring a lot of convenience when we use the set.
Defaultdict is one of the methods, that is, to add the default type to the value element of the dictionary. I have seen it before but did not pay attention to how to use it. Today I have taken a special look.
The first example is introduced in various major articles:
The Code is as follows:
Import collections as coll
Def default_factory ():
Return 'default value'
D = coll. defaultdict (default_factory, foo = 'bar ')
Print 'd: ', d
Print 'foo => ', d ['foo']
Print 'foo => ', d ['bar'] # The element whose key is 'bar' does not exist and has a default value.
The output result is as follows:
The Code is as follows:
D: defaultdict ( , {'Foo': 'bar '})
Foo => bar
Foo => default value
Conclusion: we can see that when we take an unused key in the dictionary, a value is automatically generated based on default_factory, similar to d. get ('bar', 'default value ')
A comparison example:
If the value of a map in a dictionary is a set, add two elements to the set consecutively. The original dict
The Code is as follows:
Dict_set1 = {}
# If you do not know whether the key in this field exists, you must first determine
If 'key' not in dict_set1:
Dict_set1 ['key'] = set ()
Dict_set1 ['key']. add ('20140901 ')
Dict_set1 ['key']. add ('000 ')
Print dict_set1
If defaultdict is used
The Code is as follows:
Dict_set = coll. defaultdict (set)
Dict_set ['key']. add ('000 ')
Dict_set ['key']. add ('20140901 ')
Print dict_set
The advantage is that you do not need to perform the set initialization judgment.
Two small cases
The Code is as follows:
Ss = '000000'
Dict_int = coll. defaultdict (int)
For s in ss:
Dict_int [s] + = 1
Print dict_int
'''''
The example in the official document shows that this method is simple.
Https://docs.python.org/2/library/collections.html#collections.defaultdict
>>> 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 object is useful when we perform this statistical data operation.