python 从字典中获取树视图,该字典具有anytree、rich或treelib

ifsvaxew  于 2022-12-02  发布在  Python
关注(0)|答案(1)|浏览(127)

我从https://anytree.readthedocs.io/en/latest/#阅读了手册,但我不知道如何将字典转换为树视图,有人能帮忙吗?

data = {
    'Marc': 'Udo',
    'Lian': 'Marc',
    'Dan': 'Udo',
    'Jet': 'Dan',
    'Jan': 'Dan',
    'Joe': 'Dan',
}

输出为

Udo
├── Marc
│   └── Lian
└── Dan
    ├── Jet
    ├── Jan
    └── Joe
tv6aics1

tv6aics11#

首先,您需要从您的“关系”数据字典中创建树,有很多方法可以做到这一点,但这里有一个例子:

from anytree import Node

nodes = {}
for k, v in data.items():
    nk = nodes[k] = nodes.get(k) or Node(k)
    nv = nodes[v] = nodes.get(v) or Node(v)
    nk.parent = nv

现在,您需要标识根节点,在您的示例中,它是没有父节点(Udo)的唯一节点。

[root] = [n for n in nodes.values() if n.parent is None]

# Or, if you don't need the validation that there is a unique root:
root = <any node>
while root.parent is not None:
    root = root.parent

# Or, if you already knew the root node's name then just:
root = nodes[root_name]

一旦有了根节点,就可以像这样渲染树:

>>> from anytree import RenderTree
>>> print(RenderTree(root).by_attr())
Udo
├── Marc
│   └── Lian
└── Dan
    ├── Jet
    ├── Jan
    └── Joe

anytree API比rich更丰富,因此rich.tree的API稍微复杂一些:

>>> import rich.tree
>>> nodes = {}
... for k, v in data.items():
...     nk = nodes[k] = nodes.get(k) or rich.tree.Tree(k)
...     nv = nodes[v] = nodes.get(v) or rich.tree.Tree(v)
...     nv.children.append(nk)
...     nk.parent = nv
... 
>>> [root] = [n for n in nodes.values() if getattr(n, "parent", None) is None]
>>> rich.print(root)
Udo
├── Marc
│   └── Lian
└── Dan
    ├── Jet
    ├── Jan
    └── Joe

相关问题