-1

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 :)

satish silveri
  • 358
  • 3
  • 17

2 Answers2

2

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
furas
  • 134,197
  • 12
  • 106
  • 148
1

Three things to note:

  1. you can cast anytree.Node to a string
  2. the first 6 characters of the stringified Node class is always Node(' and the last 2 characters are always ')
  3. the anytree.Node class has a separator attribute which you can use to split the stringified Node on

Combining these facts:

In [7]: node
Out[7]: Node('/A/C')

In [8]: str(_next)[6:-2].split(_next.separator)[-1]
Out[8]: 'C'
aweeeezy
  • 806
  • 1
  • 9
  • 22