1.collections.defaultdict class
from collections import defaultdict
2.collections.defaultdict Classes and factory functions dict Compare :
(1) as everyone knows , stay Python If you visit dict Keys that don't exist in the dictionary , May trigger KeyError abnormal . But sometimes , The default value of each key in the dictionary is very convenient .defaultdict You can avoid KeyError abnormal .
# 1-dict()
strings = ('puppy', 'kitten', 'puppy', 'puppy',
'weasel', 'puppy', 'kitten', 'puppy')
counts = {}
for kw in strings:
counts[kw] += 1
# 1-dict()
strings = ('puppy', 'kitten', 'puppy', 'puppy',
'weasel', 'puppy', 'kitten', 'puppy')
counts = {}
for kw in strings:
counts[kw] += 1
# Report errors
#Traceback (most recent call last):
# File "C:\Users\summer\Desktop\demo.py", line 5, in <module>
# counts[kw] += 1
#KeyError: 'puppy'
# 2-defaultdict()
from collections import defaultdict
strings = ('puppy', 'kitten', 'puppy', 'puppy',
'weasel', 'puppy', 'kitten', 'puppy')
counts = defaultdict(int)
for kw in strings:
counts[kw] += 1
print(counts)
# defaultdict(<class 'int'>, {'puppy': 5, 'kitten': 2, 'weasel': 1})
(2)default_factory Take a factory function as an argument , for example int str list set etc. .
defaultdict Class takes a type as an argument , When the accessed key does not exist , You can instantiate a value as the default value. The type of default value is determined by the factory function .
from collections import defaultdict
dic1 = defaultdict(int)
print(dic1['a'])
dic2 = defaultdict(list)
print(dic2['a'])
dic3 = defaultdict(dict)
print(dic3['a'])
0
[]
{}
(3) Returns an instance of the factory function , Then we have the corresponding method of the factory function