How is the defaultdict used in Python?
In Python, a default dictionary is a dictionary with a default value assigned to any keys in the dictionary. When accessing a non-existent key, a regular dictionary would raise a KeyError exception, while a default dictionary would return the default value.
The following is the usage method of the default dictionary:
- Import the defaultdict module.
from collections import defaultdict
- Create a default dictionary object with a specified default value type.
my_dict = defaultdict(int)
In the above example, a default dictionary object named my_dict is created with the default value type set to integer.
- Add key-value pairs:
my_dict['a'] = 1
my_dict['b'] = 2
- Accessing the value in a dictionary:
print(my_dict['a']) # 输出: 1
print(my_dict['c']) # 输出: 0(未找到键,返回默认值0)
In the example above, when accessing the existing key ‘a’, it returns the corresponding value of 1; when accessing the non-existing key ‘c’, it will return the default value of 0 due to the use of a default dictionary.
It is important to note that when initializing a default dictionary, you need to specify a default value type, such as int, list, str, etc.