从图边列表创建嵌套dict

2024-04-20 11:54:05 发布

您现在位置:Python中文网/ 问答频道 /正文

如何将图边列表转换为嵌套的层次dict?你知道吗

一些背景:我需要这个dict用于D3.js可视化。我正在尝试复制此格式:https://raw.githubusercontent.com/d3/d3-hierarchy/v1.1.8/test/data/flare.json 在集群Dendogram中使用:https://observablehq.com/@d3/cluster-dendrogram

输入(子级和父级):

[
("a", "b"),
("c", "a"),
("d", "a"),
("e", "a"),
("f", "a"),
("g", "a"),
("h", "g")
]

期望输出:

{
    "name": "b",
    "children": [
        {
            "name": "a",
            "children": [
                {"name": "c"},
                {"name": "d"},
                {"name": "e"},
                {"name": "f"},
                {
                    "name": "g",
                    "children": [
                        {"name": "h"}
                    ]
                }

            ]
        }
    ]
}

Tags: namehttpscom列表raw可视化格式js
1条回答
网友
1楼 · 发布于 2024-04-20 11:54:05

试试这个:

elements = [
    ("a", "b"),
    ("c", "a"),
    ("d", "a"),
    ("e", "a"),
    ("f", "a"),
    ("g", "a"),
    ("h", "g")
]

def create_result_element(name, children):
    if children:
        return {'name': name, 'children': children}
    else:
        return {'name': name}

def get_children(parent, a, seen):
    return [
        create_result_element(e[0], get_children(e[0], a, seen | {e[0]}))
        for e in a
        if e[1] == parent and e[0] not in seen
    ]

def create_tree(a):
    # Search for elements with no parent
    top_elements = {e[1] for e in a} - {e[0] for e in a}
    return [
        create_result_element(t, get_children(t, a, {t}))
        for t in top_elements
    ]

print(create_tree(elements))

这将打印:

[
  {
    'name': 'b',
    'children': [
      {
        'name': 'a',
        'children': [
          {'name': 'c'},
          {'name': 'd'},
          {'name': 'e'},
          {'name': 'f'},
          {
            'name': 'g',
            'children': [
              {'name': 'h'}
            ]
          }
        ]
      }
    ]
  }
]

相关问题 更多 >