You may achieve this with a recursive defaultdict
.
from collections import defaultdict
def tree():
def the_tree():
return defaultdict(the_tree)
return the_tree()
It is important to protect the default factory name, the_tree
here, in a closure ("private" local function scope). Avoid using a one-liner lambda
version, which is bugged due to Python's late binding closures, and implement this with a def
instead.
The accepted answer, using a lambda, has a flaw where instances must rely on the nested_dict
name existing in an outer scope. If for whatever reason the factory name can not be resolved (e.g. it was rebound or deleted) then pre-existing instances will also become subtly broken:
>>> nested_dict = lambda: defaultdict(nested_dict)
>>> nest = nested_dict()
>>> nest[0][1][2][3][4][6] = 7
>>> del nested_dict
>>> nest[8][9] = 10
# NameError: name 'nested_dict' is not defined