JokerMartini JokerMartini - 1 year ago 85
Python Question

Get child node if exists otherwise create in Python

I have a basic class containing two attributes 'Name' and 'Children.

class Node():
def __init__(self, name): = name
self.children = []

I have a core root node as follows:

# Create Master Root Node
root = Node('root')

How would I go about creating a function that I could pass a path to a specific node in the tree, and the function return that node.
However if that node doesn't exist it would create/append to the tree, and still return the node.

path = ['Leslie','Marie','Tori'] # simple example

def get_node_by_path(path=[])...

If a path failed before reaching the end of the path, it would automatically create the missing nodes in order to make the entire path complete.

enter image description here

path = ['Leslie','Marie','Tori','Kevin'] # more complex requires two nodes to be created

def get_node_by_path(path=[])...

enter image description here

Answer Source

I'd do something like this. It's a non recursive solution.

def get_node_by_path(path):
    cur_node = root
    for elem_name in path:
        found = False
        for child in cur_node.children:
            if == elem_name:
                cur_node = child
                found = True
        if not found:
            new_node = Node(elem_name)
            cur_node = new_node
    return cur_node
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download