【问题标题】:List of Relational Tuples Into Dictionary关系元组列表到字典中
【发布时间】:2021-07-24 08:55:21
【问题描述】:

我有以下元组列表:

[(0, 1), (1, 2), (1, 3), (3, 4), (5, 6), (4, 6)]

我想要以下嵌套字典:

{
   "0":{
      "1":{
         "2":{},
         "3":{
            "4":{
               "6":{}
            }
         }
      }
   },
   "5":{
      "6":{}
   }
}

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

【问题讨论】:

  • 你为什么想要那个?那不是树或图表。为什么要复制元素?
  • 它看起来像是某种路径变体。哪里有从 0->1->2、0->1->3->4->6、5->6 等的路径。
  • @HenryEcker,你是对的。我已经使用显示这些路径的图形图像编辑了原始问题。
  • 如果列表中有(6, 7),您希望发生什么?每个“6”都会重复一次吗?
  • @IainShelvington 是的,应该为每个“6”复制一次。

标签: python list dictionary nested tuples


【解决方案1】:

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

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: {}}}

【讨论】:

    【解决方案2】:

    你也可以使用递归:

    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: {}}}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-12
      • 2021-11-12
      • 2011-01-13
      • 1970-01-01
      相关资源
      最近更新 更多