Automatically add key to Python dict

python

Solution

Use a `collections.defaultdict`:

def recursively_default_dict():
    return collections.defaultdict(recursively_default_dict)

my_dict = recursively_default_dict()
my_dict['a']['b'] = 'c'

Problem

I want to automatically add keys to a Python dictionary if they don't exist already. For example, ``` a = "a" b = "b" c = "c" dict = {} dict[a][b] = c # doesn't work because dict[a] doesn't exist ``` How do I automatically create keys if they don't exist?

Original source