我有以下元组列表:
[(0, 1), (1, 2), (1, 3), (3, 4), (5, 6), (4, 6)]
我想要以下嵌套字典:
{
"0":{
"1":{
"2":{},
"3":{
"4":{
"6":{}
}
}
}
},
"5":{
"6":{}
}
}
应采用什么方法将上述元组列表转换为如上所示的嵌套字典? 基本上,我想将以下图形节点及其关系存储为字典。
最佳答案
使用默认字典这非常容易。只需要一些额外的逻辑来删除图中非顶级/父节点的任何节点。
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))
{0: {1: {2: {}, 3: {4: {6: {}}}}}, 5: {6: {}}}
关于python - 字典中的关系元组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67343630/