Junior — Middle
Explain how a standard Python dictionary differs from a defaultdict collection and when it is more convenient to use?
sobes.tech AI
Answer from AI
The standard dictionary (dict) in Python raises a KeyError exception when accessing a non-existent key.
defaultdict from the collections module is a subclass of dictionary that automatically creates a default value for missing keys using an initializer function.
Example:
from collections import defaultdict
# Regular dict
d = {}
# d['key'] # KeyError
# defaultdict with int (default 0)
dd = defaultdict(int)
print(dd['key']) # Outputs 0, key 'key' is automatically added
# defaultdict with list
dd_list = defaultdict(list)
dd_list['key'].append(1)
print(dd_list['key']) # [1]
defaultdict is useful when collecting data by keys without checking for the key's existence beforehand, for example, for counting or grouping.