Python defaultdict

A defaultdict is a dictionary with a default value for keys, so that keys for which no value has been explicitly defined can be accessed without errors. defaultdict is especially useful when the values in the dictionary are collections (lists, dicts, etc) in the sense that it does not need to be initialized every time when a new key is used.

A defaultdict will never raise a KeyError. Any key that does not exist gets the default value returned.

For example, consider the following dictionary 

>>> state_capitals = {
    'Arkansas': 'Little Rock',
    'Colorado': 'Denver',
    'California': 'Sacramento',
    'Georgia': 'Atlanta'

If we try to access a non-existent key, python returns us an error as follows

>>> state_capitals['Alabama']
Traceback (most recent call last):

File "<ipython-input-61-236329695e6f>", line 1, in <module> state_capitals['Alabama']

KeyError: 'Alabama'

Let us try with a defaultdict. It can be found in the collections module. 

>>> from collections import defaultdict
>>> state_capitals = defaultdict(lambda: 'Boston'

What we did here is to set a default value (Boston) in case the give key does not exist. Now populate the dict as before: 

>>> state_capitals['Alabama']

and returns the created values for existing key just like a normal dictionary

>>> state_capitals['Arkansas'

'Little Rock'