我有类似的级别列表
levels = [["A", "B", "C", "D"], ["A", "B"], ["A", "B", "X"]]
作为响应,嵌套字典应显示为
{
"name": "A",
"parent": -1,
"children": [
{
"name": "B",
"parent": "A",
"children": [
{
"name": "C",
"parent": "B",
"children": [
{
"name": "D",
"parent": "C",
}
],
},
{
"name": "X",
"parent": "B"
}
],
}
]
}
我知道我在递归循环中丢失了一些东西。
到目前为止,这是我的代码
import csv
import json
class AutoVivification(dict):
"""Implementation of perl's autovivification feature."""
def __getitem__(self, item):
try:
return dict.__getitem__(self, item)
except KeyError:
value = self[item] = type(self)()
return value
def master_tree(data, payload, parent = -1):
if len(data) == 1:
if data[0] not in payload['name']:
payload = {'name':data[0], "parent": parent}
else:
if data[0] in payload['name']:
for k in payload['children']:
master_tree(data[1:], k, data[0])
else:
payload = {'name': data[1], "parent": data[0], 'children':[master_tree(data[1:], payload, data[0])]}
return payload
payload = AutoVivification()
payload = master_tree(["A", "B", "X"], payload)
payload = master_tree(["A", "B", "C", "D"], payload)
print json.dumps(payload, indent=4)
当重复相同的结构时,会出现问题。就像第一次迭代中已经存在A-> B-> C-> D一样,当再次传递A-> B时,理想情况下应跳过它,在最后一种情况下,它应仅在B下添加X节点
最佳答案
import csv
import json
class AutoVivification(dict):
"""Implementation of perl's autovivification feature."""
def __getitem__(self, item):
try:
return dict.__getitem__(self, item)
except KeyError:
value = self[item] = type(self)()
return value
def master_tree(data, payload, parent = -1):
if len(data) == 1:
if data[0] not in payload['name']:
payload = {'name':data[0], "parent": parent}
else:
if 'name' in payload and data[0] in payload['name']:
get_list = []
for k in payload['children']:
get_list.append(k['name'])
if data[1] in get_list:
master_tree(data[1:], k, data[0])
else:
payload['children'].append(master_tree(data[1:], {'name':data[0], "parent": parent}, data[0]))
else:
payload = {'name': data[0], "parent": parent, 'children':[master_tree(data[1:], payload, data[0])]}
return payload
payload = AutoVivification()
payload = master_tree(["A", "B", "X"], payload)
payload = master_tree(["A", "B", "C", "D"], payload)
payload = master_tree(["A", "B", "Q"], payload)
print json.dumps(payload, indent=4)