我有一個下面的列表元組的列表詞典(樹): -的Python - 生成
a = [(1, 1), (2, 1), (3, 1), (4, 3), (5, 3), (6, 3), (7, 7), (8, 7), (9, 7)]
這是一個元組列表。元組內的元素的格式爲(Id, ParentId)
其根節點爲Id == ParentId
。該列表可以以元組的任何順序。
我想生成以下字典使用元組的上述名單,
output = [{
'id': 1,
'children': [{
{
'id': 3,
'children': [{
{
'id': 5
},
{
'id': 4
},
{
'id': 6
}
}]
},
{
'id': 2
}
}]
}, {
'id': 7,
'children': [{
{
'id': 9
},
{
'id': 8
}
}]
}]
即(在graphs-一個阿甘而言)
1 7
/\ /\
2 3 8 9
/|\
4 5 6
我的最終輸出應詞典給出以上。
我試過如下: -
,我已經試過解決方案如下: -
# set the value of nested dictionary.
def set_nested(d, path, value):
reduce(lambda d, k: d.setdefault(k, {}), path[:-1], d)[path[-1]] = value
return d
# returns the path of any node in list format
def return_parent(list, child):
for tuple in list:
id, parent_id = tuple
if parent_id == id == child:
return [parent_id]
elif id == child:
return [child] + return_parent(list, parent_id)
paths = []
temp = {}
for i in a:
id, parent_id = i
temp[id] = {'id': id}
path = return_parent(a, id)[::-1]
paths.append(path) # List of path is created
d = {}
for path in paths:
for n, id in enumerate(path):
set_nested(d, path[:n + 1], temp[id]) # setting the value of nested dictionary.
print d
,我得到的輸出是
{
'1': {
'3': {
'6': {
'id': '6'
},
'5': {
'id': '5'
},
'id': '3',
'4': {
'10': {
'id': '10'
},
'id': '4'
}
},
'2': {
'id': '2'
},
'id': '1'
},
'7': {
'9': {
'id': '9'
},
'8': {
'id': '8'
},
'id': '7'
}
}
我很接近到它,但不能得到確切的輸出。另外,還有更好的解決方案嗎?
只是好奇,但你保證有有效的輸入?沒有循環(例如1是2的父親,它是1的父親)? –