我有一个python字典,我想从中创建一棵树。 字典是这样的:
dict_={"2":{'parent': "1"},"1":{'parent': None},"3":{'parent': "2"}}
在这种情况下,根是“ 1”
我尝试使用treelib库,但是当我在字典上进行迭代并创建一个节点时,尚未创建其父级的问题。例如,如果我要为“ 2”创建一个节点,则尚未创建其父级(“ 1”),因此不能这样做。任何想法?
答案 0 :(得分:1)
您可以执行以下操作。首先,将数据结构转换为父子映射:
from collections import defaultdict
d = defaultdict(list) # parent: List[children]
for k, v in dict_.items():
d[v['parent']].append(k)
然后,从根开始
root = d[None][0]
tree = Tree()
tree.create_node(root, root)
从顶部创建树:
agenda, seen = [root], set([root])
while agenda:
nxt = agenda.pop()
for child in d[nxt]:
tree.create_node(child, child, parent=nxt)
if child not in seen:
agenda.append(child)
seen.add(child)
答案 1 :(得分:0)
您可以使用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。