anytree
anytree copied to clipboard
How to add a child by parent ID?
head = Node(123, id=123)
Node(456, id=456, parent=head)
print(RenderTree(head))
Node('/123', id=123)
└── Node('/123/456', id=456)
How do I add a child to the Node with ID 456?
All the examples in the documentation assume the nodes have a unique variable.
Documentation writes:
Node: a simple tree node with at least a name attribute and any number of additional attributes.
Node names don't need to be unique. The following example works for me:
...
Node(456, id=456, parent=Node) # adding a child to the Node with ID 456.
print(RenderTree(head))
# it prints the following:
Node('/123', id=123)
└── Node('/123/456', id=456)
└── Node('/123/456/456', id=456)
Parameters: name – A name or any other object this node can reference to as idendifier.
Keyword Arguments: parent – Reference to parent node.children – Iterable with child nodes. * – Any other given attribute is just stored as object attribute.
Your id here do nothing special, it is not unique, it is a simple object attribute. If you want it to be special you can extend the Node class or use NodeMixin. Write an id property with unique checking in the setter. Python @property decorator
Hope it helps :)
Just to follow-up on this question, suppose I have a pre-existing tree as shown below:
f
|-- b
| |-- a
| +-- d
| |-- c
| +-- e
+-- g
+-- i
+-- h
If I need to add another node (lets say "j") as a child to the Node "d" then what would I need to do now? I do not have access to any variable references except the root Node root= Node("f") and do not have any Id's for the nodes. Would this still be possible?
Hi, this is implemented over here.
You can do a add_path_to_tree("f/b/d/j") to add Node "j" as child of Node "d"
https://bigtree.readthedocs.io/en/latest/bigtree/tree/construct.html#bigtree.tree.construct.add_path_to_tree