Create a tree from a given dictionary(从给定的字典创建一棵树)
问题描述
我有一个 python 字典,我想用它创建一棵树.字典是这样的:
I have a python dictionary and I would like to create a tree from it. The dictionary is something like this:
dict_={"2":{'parent': "1"},"1":{'parent': None},"3":{'parent': "2"}}
在这种情况下,根是1"
in this case, the root is "1"
我尝试使用 treelib 库,但是当我在字典上迭代并创建节点时出现问题,但尚未创建其父节点.例如,如果我想为2"创建一个节点,它的父节点(1")还没有创建,所以不能这样做.任何的想法?
I tried to use treelib library but the problem when I iterate on the dictionary and create a node, its parent isn't created yet. For example, if I want to create a node for "2", its parent("1") isn't created yet, so can not do it. Any idea?
推荐答案
您可以使用 treelib 执行以下操作:
You could do the following, using treelib:
from treelib import Node, Tree
dict_ = {"2": {'parent': "1"}, "1": {'parent': None}, "3": {'parent': "2"}}
added = set()
tree = Tree()
while dict_:
for key, value in dict_.items():
if value['parent'] in added:
tree.create_node(key, key, parent=value['parent'])
added.add(key)
dict_.pop(key)
break
elif value['parent'] is None:
tree.create_node(key, key)
added.add(key)
dict_.pop(key)
break
tree.show()
输出
1
└── 2
└── 3
想法是仅当父节点存在于树中或父节点None
时才添加节点.当父为 None
时,将其添加为 root.
The idea is to add a node only if the parent is present in the tree or the parent is None
. When the parent is None
add it as root.
这篇关于从给定的字典创建一棵树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从给定的字典创建一棵树
基础教程推荐
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 筛选NumPy数组 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01