How to Import a treelib Tree from a Dictionary: Complete Guide

Use Tree.from_dict() to reconstruct a tree from a nested dictionary structure, or manually parse the dictionary using create_node() for custom import logic that handles specific node identifiers or data attributes.

The treelib library provides robust tools for tree manipulation in Python. While exporting a tree to a dictionary is straightforward with Tree.to_dict(), importing a treelib tree from a dictionary requires either the built-in Tree.from_dict() class method or a custom reconstruction function. This guide demonstrates both approaches using the actual implementation from caesar0301/treelib.

Using the Built-in Tree.from_dict() Method

The treelib source code in treelib/tree.py provides Tree.from_dict() as a class method for direct dictionary import. This method expects a nested dictionary structure matching the format produced by Tree.to_dict(), where each key represents a node tag and children are nested under a "children" key.

While the library documentation notes this method exists for reconstruction alongside Tree.from_map() (for child-parent mappings), the implementation handles the recursive parsing internally:

from treelib import Tree

# Assuming exported_dict matches the to_dict() output format

tree = Tree.from_dict(exported_dict)

Manual Dictionary Import with Custom Logic

For cases requiring custom node identifiers, data attribute handling, or dictionary formats that don't match the standard to_dict() output, manually reconstructing the tree using a recursive helper function provides flexibility. This approach uses Tree.create_node() as implemented in treelib/tree.py.

The following pattern iterates through nested dictionaries and explicitly handles the data attribute:

from treelib import Tree
import json

def dict_to_tree(d, parent=None, tree=None):
    """
    Recursively convert a nested dictionary to a treelib Tree.
    Assumes format: {tag: {'children': [...], 'data': {...}}}
    """
    if tree is None:
        tree = Tree()
    
    for tag, content in d.items():
        node_id = tag  # Using tag as identifier; customize as needed

        node_data = content.get("data")
        
        tree.create_node(tag, node_id, parent=parent, data=node_data)
        
        # Recursively process children

        for child in content.get("children", []):
            dict_to_tree(child, parent=node_id, tree=tree)
    
    return tree

# Example usage with JSON file

with open("tree.json", "r", encoding="utf-8") as fp:
    data = json.load(fp)

reconstructed_tree = dict_to_tree(data)
reconstructed_tree.show()

Importing from JSON Files

Since dictionaries are frequently serialized to JSON, the import workflow typically involves reading a JSON file and converting it to a tree. The examples/json_trees.py file in the repository demonstrates this round-trip pattern.

Combine json.load() with either Tree.from_dict() (for standard formats) or the custom dict_to_tree helper:

import json
from treelib import Tree

# Load dictionary from JSON

with open("exported_tree.json", "r", encoding="utf-8") as f:
    tree_dict = json.load(f)

# Method 1: Direct import (if format matches to_dict output)

tree = Tree.from_dict(tree_dict)

# Method 2: Custom reconstruction for modified formats

# tree = dict_to_tree(tree_dict)

Alternative Import via Tree.from_map()

For dictionary structures that represent parent-child relationships as mappings rather than nested hierarchies, treelib/tree.py provides Tree.from_map(). This method accepts a dictionary where keys are node identifiers and values are parent identifiers, which is useful for flat data structures:


# Example mapping: {child_id: parent_id, ...}

parent_map = {
    "root": None,
    "child_a": "root",
    "child_b": "root"
}

tree = Tree.from_map(parent_map)

Summary

  • Use Tree.from_dict() for direct reconstruction from nested dictionaries matching the to_dict() format in treelib/tree.py.
  • Implement a recursive helper like dict_to_tree when you need custom node IDs, data handling, or non-standard dictionary structures.
  • Leverage Tree.from_map() for flat parent-child mapping dictionaries rather than nested hierarchies.
  • Combine with json.load() to import trees from JSON files, as demonstrated in examples/json_trees.py.

Frequently Asked Questions

How do I import a treelib tree from a JSON file?

Load the JSON file using json.load() to obtain a dictionary, then pass that dictionary to Tree.from_dict() if it matches the standard export format, or use a custom recursive function like dict_to_tree() to handle specific node data or identifier requirements.

What is the difference between Tree.from_dict() and Tree.from_map()?

Tree.from_dict() expects a nested dictionary structure where children are nested under parent keys (the format produced by Tree.to_dict()), while Tree.from_map() expects a flat dictionary mapping child identifiers to parent identifiers, which is useful for importing from adjacency lists or simple parent-child tables.

Can I preserve node data when importing from a dictionary?

Yes, when using a custom import function, extract the data field from your dictionary structure and pass it to tree.create_node(tag, identifier, parent=parent, data=node_data). If using Tree.from_dict(), ensure your input dictionary includes the data keys at the appropriate nesting level if the method supports it, or use the manual reconstruction approach for full control over data attributes.

How do I handle custom node identifiers during import?

When using Tree.from_dict(), the method typically uses the dictionary keys as node tags and generates or uses internal identifiers. For custom identifier control, use the manual dict_to_tree approach shown in the examples, where you can explicitly set the node_id variable to any value extracted from your dictionary or generated according to your logic.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →