Nutree (Tree Data Structures)

1.1.0 · active · verified Sat Apr 11

Nutree is a Python library for tree data structures with an intuitive, yet powerful, API. It allows handling of arbitrary objects in a hierarchical structure, offering features like navigation, searching, filtering, serialization to JSON and DOT, diffing, and typed child nodes. The library is actively maintained with regular releases, currently at version 1.1.0.

Warnings

Install

Imports

Quickstart

This example demonstrates how to create a tree, add nodes using string data and arbitrary objects, chain `add` calls for easy construction, and pretty print the tree structure. It also shows how to access nodes by their name.

from nutree import Tree

# Create a new tree
tree = Tree("Root")

# Add nodes in a chained fashion
chapter1 = tree.add("Chapter 1")
chapter1.add("Section 1.1")
chapter1.add("Section 1.2")

# Go up to the root and add another branch
chapter2 = tree.add("Chapter 2")
chapter2.add("Section 2.1").add("Subsection 2.1.1")

# Pretty print the tree
tree.print()

# Access a node by name
section_1_1 = tree["Section 1.1"]
assert section_1_1.name == "Section 1.1"

# Add an arbitrary object as data to a node
class Task:
    def __init__(self, name, priority):
        self.name = name
        self.priority = priority
    def __str__(self):
        return f"Task({self.name}, P:{self.priority})"

task_node = chapter1.add(Task("Review Draft", 1))
assert isinstance(task_node.data, Task)

view raw JSON →