### 从图边列表创建嵌套字典

``````[
("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 个答案:

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