python - 字典中的关系元组列表

标签 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":{}
   }
}

应采用什么方法将上述元组列表转换为如上所示的嵌套字典? 基本上,我想将以下图形节点及其关系存储为字典。

enter image description here

最佳答案

使用默认字典这非常容易。只需要一些额外的逻辑来删除图中非顶级/父节点的任何节点。

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/

相关文章:

python - 未找到 Shapely parallel_offset

python - 异常消息的默认编码

python - 访问嵌套字典中的值

C# Override List<T> 添加方法来检查列表是否为空

c++ - 遍历对列表的 vector

dictionary - 在 Hazelcast 中创建另一个 map 函数?

python - OpenERP onchange 事件从父表中获取详细信息

java - 在 Java 8 中向 TreeMap 中的键添加多个值

python - 迭代字典抛出 TypeError : list indices must be integers or slices, not tuple

元组列表的 Python 字典。打印元组中的元素列表