在python循环中填写所需格式的列表

在python循环中填写所需格式的列表,python,python-3.x,Python,Python 3.x,我正在尝试在循环中创建列表结构: [children:[{text: "Title 1", id: '1', expanded: true,children: [{text: "title2", leaf: true ,},{text: "title3", leaf: true}]},{text: "Title4", id: '4', expanded: true, children: [{text: "title5", leaf: true,} ]}]] 源数据如下所示: mylist =[

我正在尝试在循环中创建列表结构:

[children:[{text: "Title 1", id: '1', expanded: true,children: [{text: "title2", leaf: true ,},{text: "title3", leaf: true}]},{text: "Title4", id: '4', expanded: true, children: [{text: "title5", leaf: true,} ]}]]
源数据如下所示:

mylist =[{'id': '1', 'name': 'Title1', 'id_parent': '0'}, {'id': '2', 'name': 'title2', 'id_parent': '1'}, {'id': '3', 'name': 'title3', 'id_parent': '1'}, {'id': '4', 'name': 'Title4', 'id_parent': '0'}, {'id': '5', 'name': 'title5', 'id_parent': '4'}]
使用递归,我遍历数据并获得父母和孩子的记录:

def get_parent(id_parent):
    c = []
    for x in mylist:
        if not x["id"] == id_parent and x["id_parent"] == id_parent:
            if x["id_parent"] == id_parent:
                x['expanded'] = True
            else:
                x['leaf'] = True
            c.append(x)
    return(c)
def get_tree(t):
    lst = []
    main_data = []
    for x in get_parent(t):
        all_stor = {}
        all_stor["text"] = x['name']
        all_stor["id"] = x['id']
        if x.get('expanded'):
            all_stor["expanded"] = x['expanded']
        else:
            all_stor["leaf"] = x['leaf']

        main_data.append(all_stor)
        lst.append([main_data, get_tree(x["id"])])
    return lst
main = get_tree("0")
print(main)

如何在循环中填充主数据列表以获得必要的结构?

您的预期输出应该是根级别的子级列表:

def get_tree(l, parent='0'):
    children = []
    for d in l:
        if d['id_parent'] == parent:
            details = {'text': d['name'], 'id': d['id']}
            grand_children = get_tree(l, d['id'])
            if grand_children:
                details.update({'expanded': True, 'children': grand_children})
            else:
                details['leaf'] = True
            children.append(details)
    return children
因此,通过示例输入,
get\u tree(mylist)
将返回:


[{'text':'Title1','id':'1','expanded':True,'children':[{'text':'title2','id':'2','leaf':True},{'text':'title3','id':'3','leaf':True},{'text':'Title4','id':'4','expanded':True,'children children:[{'text':'title5','id':'5','leaf':True}

您尝试创建的不是有效的Python数据结构。您是尝试创建dict还是列表?谢谢。您的回答对我帮助很大