defaultdict of defaultdict, nested

Creating arbitrary level of nested dictionaries using defaultdict:

from collections import defaultdict

def recursive_defaultdict():
    return defaultdict(recursive_defaultdict)
>>> x = recursive_defaultdict()
>>> x['a']['b']['c']['d']
defaultdict(<function recursive_defaultdict at 0x7fbf9b0496e0>, {})
>>> import json
>>> print json.dumps(x)
{"a": {"b": {"c": {"d": {}}}}}

With a lambda:

recursive_defaultdict = lambda: defaultdict(rec_dd)

Source: https://stackoverflow.com/questions/19189274/defaultdict-of-defaultdict-nested

Comments

Comments powered by Disqus