Python 字典中的关系元组列表
我有以下元组列表:Python 字典中的关系元组列表,python,list,dictionary,nested,tuples,Python,List,Dictionary,Nested,Tuples,我有以下元组列表: [(0,1)、(1,2)、(1,3)、(3,4)、(5,6)、(4,6)] 我需要以下嵌套字典: { "0":{ "1":{ "2":{}, "3":{ "4":{ "6":{} } } } }, "5":{ "6":{} } } 应该采用什么方法将上面的元组列表转换为如上所示的嵌套字典? 基本上,我希望将以下图形节点及其关系存储为字典 使用defaultdict很容易做到这一点。只需要一些额外的逻辑来删除图中不是顶级/父级的任何节点 from collections i
[(0,1)、(1,2)、(1,3)、(3,4)、(5,6)、(4,6)]
我需要以下嵌套字典:
{
"0":{
"1":{
"2":{},
"3":{
"4":{
"6":{}
}
}
}
},
"5":{
"6":{}
}
}
应该采用什么方法将上面的元组列表转换为如上所示的嵌套字典?
基本上,我希望将以下图形节点及其关系存储为字典
使用defaultdict很容易做到这一点。只需要一些额外的逻辑来删除图中不是顶级/父级的任何节点
from collections import defaultdict
data = [(0, 1), (1, 2), (1, 3), (3, 4), (5, 6), (4, 6)]
result = defaultdict(dict)
children = set()
for parent, child in data:
result[parent][child] = result[child]
children.add(child)
for child in children:
del result[child]
print(dict(result))
您还可以使用递归:
data = [(0, 1), (1, 2), (1, 3), (3, 4), (5, 6), (4, 6)]
def to_dict(n):
return {b:to_dict(b) for a, b in data if a == n}
r = {a:to_dict(a) for a, _ in data if not any(b == a for _, b in data)}
输出:
{0: {1: {2: {}, 3: {4: {6: {}}}}}, 5: {6: {}}}
你为什么要那样?那不是一棵树或一张图。为什么要复制元素?它看起来像是某种路径变体。这里有一条从0->1->2,0->1->3->4->6,5->6等的路径@HenryEcker,你说得对。我已经用显示这些路径的图形图像编辑了原始问题。如果列表中有
(6,7)
,您希望发生什么?是否每“6”重复一次?@IainShelvington是的,每“6”重复一次。
{0: {1: {2: {}, 3: {4: {6: {}}}}}, 5: {6: {}}}