Detailed usage in python defaultdict
Brief introduction
Ordinary dictionary, usage generally dict={}
, need only add an element of dict [element] = value that is, when invoked, too, dict [element] = xxx, but only if the element dictionary, if not in the dictionary, the error will
defaultdict of role is that when the dictionary key does not exist but was to find, but a return to the default value is not keyError
defaultdict use
defaultdict function accepts as a parameter a plant, constructed as follows:
dict =defaultdict( factory_function)
This may be factory_function list, set, str, etc., when the key function is not present, the default value of the return plant function, such as list corresponding to [], corresponding to an empty string STR, SET corresponding to the set (), int corresponds to 0, for example as follows:
from collections import defaultdict
dict1 = defaultdict(int)
dict2 = defaultdict(set)
dict3 = defaultdict(str)
dict4 = defaultdict(list)
dict1[2] ='two'
print(dict1[1])
print(dict2[1])
print(dict3[1])
print(dict4[1])
Export
0
set()
[]