Flat Rows To Nested Tree

Index rows by id, attach each child under its parent reference, and collect roots separately, turning flat rows into a nested tree in one pass.

PythonData Integrity

Code

pythonsnippet
26 lines
rows = [
    {"id": "root", "parent": None, "label": "Everything"},
    {"id": "ui", "parent": "root", "label": "UI"},
    {"id": "buttons", "parent": "ui", "label": "Buttons"},
    {"id": "api", "parent": "root", "label": "API"},
    {"id": "auth", "parent": "api", "label": "Auth"},
]

def build_tree(rows):
    """Build a nested tree from flat rows using node references, no recursion."""
    nodes = {row["id"]: {**row, "children": []} for row in rows}
    roots = []
    for node in nodes.values():
        parent = node["parent"]
        if parent is None:
            roots.append(node)
        else:
            nodes[parent]["children"].append(node)
    return roots

def render(nodes, depth=0):
    for node in nodes:
        print("  " * depth + node["label"])
        render(node["children"], depth + 1)

render(build_tree(rows))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

Everything
  UI
    Buttons
  API
    Auth

How it works

Flat Rows To Nested Tree reduces to the functions build_tree and render.

The loop for node in nodes.values() is the only repeated construct.

Caveats

  • There is nothing to install: the standard library covers the whole surface.

Putting it to use

Entry signature: def build_tree(rows)

The surface worth importing is build_tree; the helpers around it are private to the snippet.

Core lines

def render(nodes, depth=0):
    for node in nodes:
        print("  " * depth + node["label"])
        render(node["children"], depth + 1)
if parent is None:
    roots.append(node)

Interactive Tools for This Topic

FAQ

Any setup needed beyond the language runtime?
None — the language runtime is the only requirement. The file defines `build_tree`, `render` at load time.