defaultdict
时间: 2023-09-02 17:07:18 浏览: 31
defaultdict is a subclass of the built-in dict class in Python. It overrides one method, __missing__, to provide a default value for a nonexistent key. This makes it easier to work with dictionaries where you want to return a default value if the key is not found.
When creating a defaultdict, you can specify the default value for any new keys that are added to the dictionary. This can be done by passing a callable as the argument to the defaultdict constructor. The callable will be invoked whenever a new key is accessed for the first time, and the value it returns will be used as the default value for that key.
Here's an example:
```
from collections import defaultdict
d = defaultdict(int)
d['a'] = 1
d['b'] = 2
print(d['a']) # 1
print(d['b']) # 2
print(d['c']) # 0 (default value for int is 0)
```
In this example, we create a defaultdict with the default value of 0. We add two keys to the dictionary, 'a' and 'b', and set their values to 1 and 2, respectively. When we try to access the key 'c', which does not exist in the dictionary, the defaultdict returns the default value of 0 instead of raising a KeyError.