Trees in defaultdict(s)
Python's defaultdict
is pretty much perfect for building trees, here is a little demo.
from collections import defaultdict
once_nested = defaultdict(lambda: defaultdict(dict))
twice_nested = defaultdict(lambda: defaultdict(lambda: defaultdict(dict)))
But this simplistic approach, like the names indicate, has an upper bound for depth of the tree.
What if we want arbitrarily deep trees ? Recursion to the rescue.
class recursive_defaultdict(defaultdict):
def __init__(self):
super().__init__(recursive_defaultdict)
With this implementation, we subclass defaultdict
to provide another defaultdict
as default value, infinitely.
tree = recursive_defaultdict()
tree["and"]["now"]["we"]["can"]["go"]["all"]["the"]["way"]["down"] = "yay!"