The Python standard library has a lot of collections on the data structures of collection types, which can be a lot of convenience when we use collections, and it's good to see more.
Defaultdict is one of the methods to add the default type to the dictionary value element, which has been seen before but is not paid attention to.
First is the first example of the 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 ' #key为 ' bar ' element does not exist, there will be a default value
The output is this:
The code is as follows:
D:defaultdict ( , {' foo ': ' Bar '})
Foo=> Bar
foo=> Default Value
Conclusion: You can see here that when we take a key that is not in the dictionary, we automatically generate a value based on default_factory, similar to D.get (' bar ', ' default value ')
An example of a comparison:
If the value of a map in a dictionary is a set, add two elements to the set consecutively, using the original Dict.
The code is as follows:
Dict_set1 = {}
#如果不知道这个字段中key有没有, you need to judge
If ' key ' not in Dict_set1:
dict_set1[' key '] = set ()
dict_set1[' key '].add (' 111 ')
dict_set1[' key '].add (' 000 ')
Print Dict_set1
If you use Defaultdict, that's it.
The code is as follows:
Dict_set = Coll.defaultdict (set)
dict_set[' key '].add (' 000 ')
dict_set[' key '].add (' 111 ')
Print Dict_set
The advantage is that you do not need to do a set initialization of this judgment.
Two small cases of use
The code is as follows:
SS = ' 1111222233334444 '
Dict_int = coll.defaultdict (int)
For s in SS:
Dict_int[s] + = 1
Print Dict_int
'''''
This example of an official document can see the simplicity of this notation.
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 works well when we do this statistic-like data operation.