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 word in wordlist: Frequencies[word] + = 1
Python throws a Keyerror exception because the dictionary index must be initialized before it can be resolved with the following method
For word in wordlist: try: Frequencies[word] + = 1 except Keyerror: Frequencies[word] = 1
For word in wordlist: if Word in frequencies: Frequencies[word] + = 1 else: Frequencies[word] = 1
Of course, collections.defaultdict can also easily solve this problem.
From collections Import defaultdictfrequencies = defaultdict (int) #传入int () function to initialize for word in wordlist: frequencies[ Word] + = 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
Reference: https://www.cnblogs.com/duyang/p/5065418.html
Python collections.defaultdict