Nested Defaultdict (tree) In Python

The collections.defaultdict is very useful for well tested code as it cleans up a lot of try-except blocks when dealing with dictionaries. Singly nested dictionary can be done by collections.defaultdict(collections.defaultdict). But what about multi-layer nested dictionary?

Essentially I want to do this:

data_dict = nested_defaultdict()
data_dict['A']['B']['C']['D'] = 1

without having to initialise data_dict['A'], data_dict['A']['B'] etc.

A recursive function would do. And this is pickle-able too.

import collections

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

Update (Dec 8, 2014): I just learned that this is called autovivification. Very interesting. The Python example there is basically the same as the one presented here.

blog comments powered by Disqus