Defaultdict¶
If you try to read a value for a non-existent key from a regular dictionary, a KeyError exception will be raised (exceptions will be covered later). Defaultdict allows you to avoid writing exception handlers, and instead treats reading a non-existent key as a command to write and return a default value for that key; for example, defaultdict(int) will return 0 because the default value for the int type is 0.
In [ ]:
from collections import defaultdict
dd = defaultdict(int)
print(dd[10]) # Printing an int will output zero, the default value
dd = {} # "Normal" empty dictionary
# print(dd[10]) # Will raise a KeyError
0