pythontreeanytree

Get parent node name in anytree


I have created a tree using anytree for my custom taxonomy and I am able to search the tree using:

from anytree import find
name='c'
find(root, lambda node: node.name == name)

This returns an object of Node class that looks something like this:

Node('/f/b/d')

So, for child c, d is the immediate parent and I just want to extract 'd' and not the entire path mentioned above.

Any help would be appreciated :)


Solution

  • You can get .parent.name

    You can even get grandparent name .parent.parent.name (if only exists)

    from anytree import Node
    from anytree import find
    
    root = Node("f")
    b = Node("b", parent=root)
    d = Node("d", parent=b)
    c = Node("c", parent=d)
    
    name='c'
    result = find(root, lambda node: node.name == name)
    
    print('result Node:', result)
    
    if result.parent:
        print('parent name:', result.parent.name)
    
    if result.parent and result.parent.parent:
        print('grandparent:', result.parent.parent.name)
    

    Result:

    result Node: Node('/f/b/d/c')
    parent name: d
    grandparent: b