Anytree

2.13.0 · active · verified Thu Apr 09

Anytree is a powerful and lightweight Python library that provides a tree data structure with various plugins. It simplifies the creation, manipulation, and visualization of hierarchical data. The library is actively maintained with regular releases, approximately every few months, and is currently at version 2.13.0.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a tree using `anytree.Node` objects, either by assigning parents incrementally or by defining the full hierarchy with the `children` keyword. It then uses `RenderTree` to print a visual representation of the tree structure to the console.

from anytree import Node, RenderTree

# Create nodes by specifying parent
udo = Node("Udo")
marc = Node("Marc", parent=udo)
lian = Node("Lian", parent=marc)
dan = Node("Dan", parent=udo)
jet = Node("Jet", parent=dan)
jan = Node("Jan", parent=dan)
joe = Node("Joe", parent=dan)

# Or create a complex tree structure directly using children keyword
root_complex = Node("root", children=[
    Node("sub0", children=[
        Node("sub0B", foo=4, bar=109),
        Node("sub0A")
    ]),
    Node("sub1", children=[
        Node("sub1A"),
        Node("sub1B", bar=8),
        Node("sub1C", children=[
            Node("sub1Ca")
        ])
    ])
])

# Render the tree
for pre, fill, node in RenderTree(root_complex):
    print(f"{pre}{node.name}")

view raw JSON →