Nested Defaultdict (tree) In Python
14 July 2014
Warning If KeyError is useful for your debugging, defaultdict may not be something you want to use.
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
. But what about multi-layer nested dictionary?1
collections.defaultdict(collections.defaultdict)
Essentially I want to do this:
without having to initialise
, 1
data_dict['A']
etc.1
data_dict['A']['B']
A recursive function would do. And this is pickle-able too.
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.