A beginner Python/programming question... I'd like to build a tree structure in Python, preferably based on dictionaries. I found code that does this neatly:
Tree = lambda: collections.defaultdict(Tree)
root = Tree()
This can easily be populated like:
root['toplevel']['secondlevel']['thirdlevel'] = 1
root['toplevel']['anotherLevel'] = 2
...etc.
I'd like to populate the levels/leaves dynamically so that I can add as many levels as needed, and where the leaves can be at any level. How do I do that?
Any help is greatly appreciated.
解决方案
You can simply do it with a utility function, like this
def add_element(root, path, data):
reduce(lambda x, y: x[y], path[:-1], root)[path[-1]] = data
You can use it, like this
import collections
tree = lambda: collections.defaultdict(tree)
root = tree()
add_element(root, ['toplevel', 'secondlevel', 'thirdlevel'], 1)
add_element(root, ['toplevel', 'anotherlevel'], 2)
print root
Output
defaultdict( at 0x7f1145eac7d0>,
{'toplevel': defaultdict( at 0x7f1145eac7d0>,
{'secondlevel': defaultdict( at 0x7f1145eac7d0>,
{'thirdlevel': 1}),
'anotherlevel': 2
})
})
If you want to implement this in recursive manner, you can take the first element and get the child object from current root and strip the first element from the path, for the next iteration.
def add_element(root, path, data):
if len(path) == 1:
root[path[0]] = data
else:
add_element(root[path[0]], path[1:], data)