Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

get tree view from a dictionary with anytree lib

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading