How can I get Python to automatically create missing key/value pairs in a dictionary?

As others have said, use defaultdict. This is the idiom I prefer for arbitrarily-deep nesting of dictionaries:

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

d = nested_dict()
d[1][2][3] = 'Hello, dictionary!'
print(d[1][2][3]) # Prints Hello, dictionary!

This also makes checking whether an element exists a little nicer, too, since you may no longer need to use get:

if not d[2][3][4][5]:
    print('That element is empty!')

This has been edited to use a def rather than a lambda for pep8 compliance. The original lambda form looked like this below, which has the drawback of being called <lambda> everywhere instead of getting a proper function name.

>>> nested_dict = lambda: collections.defaultdict(nested_dict)
>>> d = nested_dict()
>>> d[1][2][3]
defaultdict(<function <lambda> at 0x037E7540>, {})

Tags:

Python