I read the manual from https://anytree.readthedocs.io/en/latest/#, but I didn’t figure out how to translate a dictionary to tree view, anyone can help?
data = {
'Marc': 'Udo',
'Lian': 'Marc',
'Dan': 'Udo',
'Jet': 'Dan',
'Jan': 'Dan',
'Joe': 'Dan',
}
output is
Udo
├── Marc
│ └── Lian
└── Dan
├── Jet
├── Jan
└── Joe
>Solution :
First you need to create the tree from your dict of "relationship" data, there are many ways to do this but here’s an example:
from anytree import Node
nodes = {}
for k, v in data.items():
nk = nodes[k] = nodes.get(k, Node(k))
nv = nodes[v] = nodes.get(v, Node(v))
nk.parent = nv
Now you need to identify the root node, in your case it is the unique node which has no parent (Udo).
[root] = [n for n in nodes.values() if n.parent is None]
Once you have the root node, you can render the tree like this:
>>> from anytree import RenderTree
>>> print(RenderTree(root).by_attr())
Udo
├── Marc
│ └── Lian
└── Dan
├── Jet
├── Jan
└── Joe