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

python

I'm creating a dictionary structure that is several levels deep. I'm trying to do something like the following:

dict = {}
dict['a']['b'] = True

At the moment the above fails because key 'a' does not exist. At the moment I have to check at every level of nesting and manually insert an empty dictionary. Is there some type of syntactic sugar to be able to do something like the above can produce:

{'a': {'b': True}}

Without having to create an empty dictionary at each level of nesting?

Best Solution

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>, {})