A Python implementation of tree data structure with hierarchical organization and efficient operations for traversal, modification, search, and visualization.
npx @tessl/cli install tessl/pypi-treelib@1.8.0A comprehensive Python library for creating, manipulating, and visualizing hierarchical tree data structures. treelib provides an intuitive API with O(1) node access, multiple traversal algorithms, rich visualization options, and efficient operations for building tree-based applications.
pip install treelibfrom treelib import Node, Treefrom treelib import Tree
# Create a new tree
tree = Tree()
# Build tree structure
tree.create_node("Company", "company")
tree.create_node("Engineering", "eng", parent="company")
tree.create_node("Sales", "sales", parent="company")
# Add team members
tree.create_node("Alice", "alice", parent="eng")
tree.create_node("Bob", "bob", parent="eng")
tree.create_node("Carol", "carol", parent="sales")
# Display the tree
tree.show()
# Traverse all nodes
for node_id in tree.expand_tree():
print(f"Visiting: {tree[node_id].tag}")
# Find specific nodes
eng_team = tree.children("eng")
all_employees = [tree[node].tag for node in tree.expand_tree()
if tree.level(node) > 1]
# Export to JSON
json_data = tree.to_json()treelib follows a dual-class architecture optimized for flexibility and performance:
Key design principles:
Create trees, add nodes, and build hierarchical structures with automatic relationship management and validation.
# Tree creation
def __init__(tree=None, deep=False, node_class=None, identifier=None): ...
# Node creation and addition
def create_node(tag=None, identifier=None, parent=None, data=None) -> Node: ...
def add_node(node, parent=None) -> None: ...
# Node access
def get_node(nid) -> Node | None: ...
def __getitem__(key) -> Node: ...
def __contains__(identifier) -> bool: ...Navigate and traverse trees using multiple algorithms including depth-first, breadth-first, and zigzag patterns with filtering and sorting options.
# Tree traversal
def expand_tree(nid=None, mode=DEPTH, filter=None, key=None, reverse=False, sorting=True) -> Iterator[str]: ...
def rsearch(nid, filter=None) -> Iterator[str]: ...
# Structure queries
def children(nid) -> list[Node]: ...
def parent(nid) -> Node | None: ...
def siblings(nid) -> list[Node]: ...
def leaves(nid=None) -> list[Node]: ...
# Tree metrics
def size(level=None) -> int: ...
def depth(node=None) -> int: ...
def level(nid, filter=None) -> int: ...Modify tree structure dynamically with move, remove, copy, and paste operations while maintaining data integrity.
# Tree modification
def move_node(source, destination) -> None: ...
def remove_node(identifier) -> int: ...
def update_node(nid, **attrs) -> None: ...
# Tree operations
def subtree(nid, identifier=None) -> Tree: ...
def remove_subtree(nid, identifier=None) -> Tree: ...
def paste(nid, new_tree, deep=False) -> None: ...
def merge(nid, new_tree, deep=False) -> None: ...Export trees to multiple formats including JSON, dictionaries, and GraphViz DOT for integration with other systems and visualization tools.
# Data export
def to_dict(nid=None, key=None, sort=True, reverse=False, with_data=False) -> dict: ...
def to_json(with_data=False, sort=True, reverse=False) -> str: ...
def to_graphviz(filename=None, shape="circle", graph="digraph", filter=None, key=None, reverse=False, sorting=True) -> None: ...
# Tree creation from data
@classmethod
def from_map(cls, child_parent_dict, id_func=None, data_func=None) -> Tree: ...Rich tree visualization with customizable display formats, line styles, filtering, and file export capabilities.
# Tree display
def show(nid=None, level=ROOT, idhidden=True, filter=None, key=None, reverse=False,
line_type="ascii-ex", data_property=None, stdout=True, sorting=True) -> str | None: ...
def save2file(filename, nid=None, level=ROOT, idhidden=True, filter=None, key=None,
reverse=False, line_type="ascii-ex", data_property=None, sorting=True) -> None: ...ROOT = 0 # Tree traversal starting from root level
DEPTH = 1 # Depth-first traversal mode
WIDTH = 2 # Breadth-first traversal mode
ZIGZAG = 3 # Zigzag traversal modeADD = 0 # Add child to node
DELETE = 1 # Delete child from node
INSERT = 2 # Insert child (deprecated, use ADD)
REPLACE = 3 # Replace child with anotherclass Node:
def __init__(tag=None, identifier=None, expanded=True, data=None): ...
# Class constants
ADD = 0 # Add child to node
DELETE = 1 # Delete child from node
INSERT = 2 # Insert child (deprecated, use ADD)
REPLACE = 3 # Replace child with another
# Properties
identifier: str # Unique node identifier
tag: str # Human-readable display name
expanded: bool # Controls visibility in displays
data: Any # User-defined payload
# Relationship query methods
def predecessor(tree_id) -> str | None: ...
def successors(tree_id) -> list[str]: ...
def is_leaf(tree_id=None) -> bool: ...
def is_root(tree_id=None) -> bool: ...
# Relationship management methods
def set_predecessor(nid, tree_id) -> None: ...
def set_successors(value, tree_id=None) -> None: ...
def update_successors(nid, mode=ADD, replace=None, tree_id=None) -> None: ...
# Tree context management
def clone_pointers(former_tree_id, new_tree_id) -> None: ...
def reset_pointers(tree_id) -> None: ...
def set_initial_tree_id(tree_id) -> None: ...
# Special methods
def __lt__(other) -> bool: ... # Less-than comparison for sorting
def __repr__() -> str: ... # Detailed string representationclass NodePropertyError(Exception): ... # Base node attribute error
class NodeIDAbsentError(NodePropertyError): ... # Node identifier doesn't exist
class NodePropertyAbsentError(NodePropertyError): ... # Node data property not specified
class MultipleRootError(Exception): ... # Multiple root nodes detected
class DuplicatedNodeIdError(Exception): ... # Duplicate node identifier
class LoopError(Exception): ... # Circular reference detected
class LinkPastRootNodeError(Exception): ... # Invalid root node operation
class InvalidLevelNumber(Exception): ... # Invalid level number specified