Is there a way to make a defaultdict also be the default for the defaultdict? (i.e. infinite-level recursive defaultdict?)
I want to be able to do:
x
Similar to BrenBarn's solution, but doesn't contain the name of the variable tree
twice, so it works even after changes to the variable dictionary:
tree = (lambda f: f(f))(lambda a: (lambda: defaultdict(a(a))))
Then you can create each new x
with x = tree()
.
For the def
version, we can use function closure scope to protect the data structure from the flaw where existing instances stop working if the tree
name is rebound. It looks like this:
from collections import defaultdict
def tree():
def the_tree():
return defaultdict(the_tree)
return the_tree()