Python collections.defaultdict () Notes

Disclaimer: the author is limited, blog inevitably a lot of flaws and even serious mistakes, I hope you correct. While writing the biggest goal is also to exchange learning, not paying attention and spread. Long way to go, and you encourage each other. https://blog.csdn.net/yexiaohhjk/article/details/88775624

The difference with the dict

In fact defaultdict explanation is that the data type container module, essentially a dictionary (dict), but the python automatically assigned an initial value for its key.
Why do you want to define a container like this?
Because in Python dict dictionary is accessed via Key, when Key does not exist, it will lead to 'KeyError' exception. To avoid this, it is possible to use a defaultdict () method in class collections to provide default values for the dictionary.

For example, you want to calculate the frequency:

wordlist = ['a','b','b','c','e','e','e']
frequencies = {}
for word in wordlist:
    frequencies[word] += 1

python will throw a KeyError exception because the index must be initialized before the dictionary can be solved using the following method:

wordlist = ['a','b','b','c','e','e','e']
frequencies = {}
for word in wordlist:
    try:
        frequencies[word] += 1
    except Exception:
        frequencies[word] = 1
print('word:',frequencies)
wordlist = ['a','b','b','c','e','e','e']
for word in wordlist:
    if word in frequencies:
        frequencies[word] += 1
    else:
        frequencies[word] = 1

collections.defaultdict使用

The collections.defaultdict can easily solve this problem:

from collections import defaultdict
wordlist = ['a','b','b','c','e','e','e']
frequencies = defaultdict(int)
for word in wordlist:
    frequencies[word] += 1

collections.defaultdict can accept a function as a parameter to initialize. We want to frequencies [word] is initialized to 0, then you can use a int()built-in function as a parameter to defaultdict, we called with no arguments int (), int () returns a 0 value. At the same time you can also use python other types of built-in functions list()and the like as parameters.
such as:

import collections
s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
# defaultdict
d = collections.defaultdict(list)
for k, v in s:
    d[k].append(v)
# Use dict and setdefault   
g = {}
for k, v in s:
    g.setdefault(k, []).append(v)

Here setdefault()you can also achieve the role of the default initialization dict type:
if the key does not exist in the dictionary, it will add the value of the key and default is set to the default value of the key, if the key exists in the dictionary, read out the original key value corresponding to, default value is not covered with the already existing bond.

dict.setdefault(key, default=None)

About setdefault()more usage can watch blog .

Guess you like

Origin blog.csdn.net/yexiaohhjk/article/details/88775624