How to Export a treelib Tree to a Dictionary: Complete Guide to `to_dict()`
Use the Tree.to_dict() method in treelib to serialize any tree structure into a nested Python dictionary, with optional parameters to control sorting, data inclusion, and subtree selection.
The treelib library (maintained in the caesar0301/treelib repository) provides a robust Tree class for managing hierarchical data. When you need to export a treelib tree to a dictionary for JSON serialization, API responses, or data interchange, the built-in to_dict() method handles the conversion efficiently.
Understanding the Tree.to_dict() Method
The to_dict() method performs a depth-first traversal of the tree (or breadth-first when sorting is enabled) and constructs a nested dictionary structure. Each node's tag becomes a key, with children stored under a "children" list.
Method Signature and Parameters
Located in treelib/tree.py at lines 51-80, the method signature is:
def to_dict(self, nid=None, key=None, sort=True, reverse=False, with_data=False)
| Parameter | Type | Description |
|---|---|---|
nid |
Optional[str] |
Node identifier for the subtree root; defaults to the tree's root node. |
key |
Optional[Callable] |
Function for sorting children (e.g., lambda n: n.tag). |
sort |
bool |
Whether to sort children before exporting (default: True). |
reverse |
bool |
Reverse the sort order (default: False). |
with_data |
bool |
Include each node's data attribute in the output (default: False). |
Source Implementation
The core logic resides in [treelib/tree.py](https://github.com/caesar0301/treelib/blob/master/treelib/tree.py). The method recursively processes nodes, building dictionaries that preserve the hierarchical relationships established by the tree structure.
Basic Examples: Export a treelib Tree to a Dictionary
Export Tree Structure Only
The simplest use case exports just the node tags and hierarchy:
from treelib import Tree
tree = Tree()
tree.create_node("Root", "root")
tree.create_node("Child A", "a", parent="root")
tree.create_node("Child B", "b", parent="root")
# Export to dictionary
tree_dict = tree.to_dict()
print(tree_dict)
Output:
{'Root': {'children': [{'Child A': {'children': []}},
{'Child B': {'children': []}}]}}
Include Node Data Attributes
When nodes carry additional payload data, use with_data=True to preserve it:
tree.create_node("Data Node", "data", parent="root",
data={"type": "important", "value": 42})
tree_dict_with_data = tree.to_dict(with_data=True)
print(tree_dict_with_data)
Output:
{'Root': {'children': [...], 'data': None},
'Data Node': {'children': [], 'data': {'type': 'important', 'value': 42}}}
Export Specific Subtrees
To export only a portion of the tree, specify the starting node ID with nid:
subtree_dict = tree.to_dict(nid="a") # Export only Child A's descendants
print(subtree_dict)
This returns a dictionary rooted at "Child A", excluding siblings and ancestors.
Advanced Configuration Options
Sorting Children During Export
By default, to_dict() sorts children to ensure consistent output. Control this behavior with the sort and reverse parameters:
# Alphabetical order (default)
sorted_dict = tree.to_dict(sort=True)
# Reverse alphabetical
reverse_dict = tree.to_dict(sort=True, reverse=True)
# Preserve insertion order (Python 3.7+)
unsorted_dict = tree.to_dict(sort=False)
Custom Sort Keys
For complex sorting logic, pass a callable to the key parameter. This function receives a node object and should return a comparable value:
# Sort by node creation time (if stored in data)
sorted_by_time = tree.to_dict(
key=lambda node: node.data.get("timestamp", ""),
sort=True
)
# Sort by identifier length, then alphabetically
sorted_complex = tree.to_dict(
key=lambda node: (len(node.identifier), node.tag.lower()),
sort=True
)
Persisting and Reloading Tree Data
Save to JSON File
The dictionary output is immediately compatible with JSON serialization:
import json
with open("tree.json", "w", encoding="utf-8") as fp:
json.dump(tree.to_dict(with_data=True), fp, ensure_ascii=False, indent=2)
This produces a human-readable JSON file that preserves the full tree structure and node data.
Reconstruct Tree from Dictionary
While treelib provides Tree.from_dict() for direct reconstruction, you can also implement custom loaders for specific dictionary formats:
from treelib import Tree
def dict_to_tree(d, parent=None, tree=None):
"""Recursively convert a to_dict() output back to a Tree."""
if tree is None:
tree = Tree()
for tag, content in d.items():
node_id = tag # In production, use unique IDs
node_data = content.get("data")
tree.create_node(tag, node_id, parent=parent, data=node_data)
for child in content.get("children", []):
dict_to_tree(child, parent=node_id, tree=tree)
return tree
# Usage
with open("tree.json") as fp:
data = json.load(fp)
reconstructed = dict_to_tree(data)
reconstructed.show()
For standard use cases, prefer the built-in Tree.from_dict() method, which handles the format produced by to_dict() automatically.
Summary
- Use
Tree.to_dict()to export a treelib tree to a dictionary, located intreelib/tree.pyat lines 51-80. - Control the export scope with the
nidparameter to export specific subtrees. - Preserve node data by setting
with_data=Trueto include thedataattribute in the output. - Sort output consistently using
sort,reverse, andkeyparameters for ordered serialization. - Integrate with JSON by passing the dictionary directly to
json.dump()for persistent storage. - Reconstruct trees using
Tree.from_dict()or custom loaders that parse the nested structure.
Frequently Asked Questions
How do I export only a specific branch of a treelib tree to a dictionary?
Pass the node identifier to the nid parameter of to_dict(). For example, tree.to_dict(nid="child_node_id") exports only the subtree rooted at that node, excluding siblings and ancestors. This is useful when you need to serialize specific sections of large hierarchical datasets.
Can I include custom data attached to nodes when exporting to a dictionary?
Yes, set the with_data=True parameter when calling to_dict(). By default, only the node tags and hierarchy are exported. When with_data is enabled, each dictionary entry includes a "data" key containing the node's associated data payload, making it suitable for complex object serialization.
How do I maintain a specific order when exporting a treelib tree to a dictionary?
Use the sort, reverse, and key parameters to control ordering. Set sort=True (default) for alphabetical ordering by tag, reverse=True to invert the order, or provide a custom key function (e.g., lambda n: n.data.get("priority")) to sort by specific node attributes. Set sort=False to preserve insertion order.
Is the dictionary format compatible with JSON serialization?
Yes, the output of to_dict() is immediately compatible with Python's json module. The method returns standard Python dictionaries, lists, and primitive types that json.dump() can serialize without modification. Use with_data=True if you need to ensure node data (which must itself be JSON-serializable) is included in the exported file.
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:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →