pythontreetreelib

Treelib does not show hierarchical tree node data


Using tree package treelib in Python I define a small tree that is slightly modified from the description for command show:

from treelib import Tree
tree = Tree()
tree.create_node("Root", "root")
tree.create_node("Child A", "a", parent="root",data={"name":"Mark"})
tree.create_node("Child B", "b", parent="root",data={"name":"Bob"})

Here I have used that data should be defined like a dictionary, as can be seen in the description:

Creating nodes with different configurations:

# Basic node
node = Node("Root", "root")

# Node with custom data
node = Node("File", "file1", data={"size": 1024, "type": "txt"})

# Node that starts collapsed
node = Node("Folder", "folder1", expanded=False)

I can graphically display the tree:

tree.show()

Root
├── Child A
└── Child B

Instead of the tags I want to graphically display the data. Let's first return the data of a single node:

print(tree.get_node('a').data)
output: {'name': 'Mark'}

Now display the whole tree data as explained in the description:

# Show custom data property
tree.show(data_property="name")  # If node.data.name exists
tree.show(data_property="name")

I get AttributeError: 'dict' object has no attribute 'name'. How to graphically display the data of the tree nodes with treelib?

Python 3.12.4, treelib 1.8.0, Spyder 6.0.7


Solution

  • It looks like tree.show demands data_property to be a straght node attribute, not some value of dictionary. You can acheive this by defining your class with properties and assigning it to nodes' data. Besides, to make tree.show work, you need to make sure that all your nodes, including root, have this property.

    from treelib import Tree
    from dataclasses import dataclass
    
    @dataclass
    class Node_data:
        name: str
    
    
    tree = Tree()
    tree.create_node("Root", "root", data=Node_data("Root"))
    tree.create_node("Child A", "a", parent="root",data=Node_data("Mark"))
    tree.create_node("Child B", "b", parent="root",data=Node_data("Bob"))
    print(tree.get_node('a').data.name)
    
    Mark
    
    tree.show(data_property="name")
    
    Root
    ├── Mark
    └── Bob