Nested defaultdict of defaultdict Nested defaultdict of defaultdict python python

Nested defaultdict of defaultdict


The other answers here tell you how to create a defaultdict which contains "infinitely many" defaultdict, but they fail to address what I think may have been your initial need which was to simply have a two-depth defaultdict.

You may have been looking for:

defaultdict(lambda: defaultdict(dict))

The reasons why you might prefer this construct are:

  • It is more explicit than the recursive solution, and therefore likely more understandable to the reader.
  • This enables the "leaf" of the defaultdict to be something other than a dictionary, e.g.,: defaultdict(lambda: defaultdict(list)) or defaultdict(lambda: defaultdict(set))


For an arbitrary number of levels:

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

Of course you could also do this with a lambda, but I find lambdas to be less readable. In any case it would look like this:

rec_dd = lambda: defaultdict(rec_dd)


There is a nifty trick for doing that:

tree = lambda: defaultdict(tree)

Then you can create your x with x = tree().