Why not? Just yesterday, I implemented a similar data structure for storing and retrieving a hierarchy of objects and considered this exact situation. The use of the Node object with a dictionary for children has ended. The main Node, which is the object, allows you to create your own methods for printing or receiving material, and if necessary you can even have lazy initialization (did you mention the large data set correctly?)
class Node(object): def __init__(self): self.children = collections.defaultdict(lambda:self.__class__()) self.stuff = ... def __str__(self,depth=0): if self.children: return str(self.stuff)+'\n'+'\n'.join([' '*depth+k+' ' + v.__str__(depth+1) for k,v in self.children.items()]) else: return str(self.stuff) def get_path(self,path): node = self while path: node = node.children[path.pop(0)] ...
source share