In fact, Defaultdict is a dictionary, but Python automatically assigns an initial value to its key. That is to say, you do not display the key for the dictionary to assign the initial value Python will not error, see the actual example.
For example, you want to calculate frequency
frequencies = {} for in wordlist: + = 1
Python throws a Keyerror exception because the dictionary index must be initialized before it can be resolved with the following method
for inch wordlist: Try : + = 1 except keyerror := 1
for inch wordlist: if inch Frequencies: + = 1 else: = 1
Of course, collections.defaultdict can also easily solve this problem.
from Import # incoming int () function to initialize for in wordlist: + = 1
Collections.defaultdict can accept a function as a parameter to initialize. What do you mean, look at the example above, we want Frequencies[word] to initialize to 0, then we can use an int () function as a parameter to defaultdict, we call int () without arguments, int () will return a 0 value
Python Collections.defaultdict Notes