从图边列表创建嵌套字典

时间:2019-05-09 09:37:57

标签: python

如何将图边缘列表转换为嵌套的分层字典?

一些背景:D3.js可视化需要这个字典。我正在尝试复制以下格式:https://raw.githubusercontent.com/d3/d3-hierarchy/v1.1.8/test/data/flare.json 在簇形图中使用: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"}
                    ]
                }

            ]
        }
    ]
}

1 个答案:

答案 0 :(得分:3)

尝试一下:

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'}
            ]
          }
        ]
      }
    ]
  }
]