【问题标题】:Python - How to convert a list of dictionaries with tree items? [closed]Python - 如何使用树项转换字典列表? [关闭]
【发布时间】:2018-12-20 15:11:25
【问题描述】:

我有一个带有 id 链接的字典列表:

[
    { 'id': 1, 'parent_id': None,   'title': '1', },
    { 'id': 3, 'parent_id': 1,  'title': '1.1', },
    { 'id': 5, 'parent_id': 4,  'title': '1.2.1', },
    { 'id': 2, 'parent_id': None,   'title': '2', },
    { 'id': 4, 'parent_id': 1,  'title': '1.2', }
]

我需要创建一个如下所示的树对象:

[
    { 'id': 1,'title': '1', 'children': [
                    {'id': 3, 'title': '1.1', 'children': []},
                    {'id': 4, 'title': '1.2', 'children': [
                                {'id': 5, 'title': '1.2.1', 'children': []},
                                                        ]},
                                    ]},
    { 'id': 2,  'title': '2', 'children': []},
]

我如何在 Python 中做到这一点?感谢您的帮助!

UPD 我试过这个,但我不知道如何编写在 2 级以上工作的代码。

    for element in elements_list:
    if not element.get('parent_id'):
        menu.append({
            'id': element.get('id'),
            'title': element.get('title'),
            'children': []
        })
    else:
        for item in menu:
            if item.get('id') == element.get('parent_id'):
                item.get('children').append({
                    'title': element.get('title'),
                    'children': []
                })

【问题讨论】:

标签: python dictionary recursion


【解决方案1】:

你可以使用递归:

[{'id': 1, 'parent_id': None, 'title': '1'}, {'id': 3, 'parent_id': 1, 'title': '1.1'}, {'id': 5, 'parent_id': 4, 'title': '1.2.1'}, {'id': 2, 'parent_id': None, 'title': '2'}, {'id': 4, 'parent_id': 1, 'title': '1.2'}]
def _filter(_d):
  return {a:b for a, b in _d.items() if a != 'parent_id'}

def group_vals(_d, _start = None):
  return [_filter({**i, 'children':group_vals(_d, i['id'])})
         for i in _d if i['parent_id'] == _start]

print(group_vals(d))

输出:

[{'id': 1, 'title': '1', 'children': [
     {'id': 3, 'title': '1.1', 'children': []}, 
     {'id': 4, 'title': '1.2', 'children': [{'id': 5, 'title': '1.2.1', 'children': []}]}]}, 
  {'id': 2, 'title': '2', 'children': []}]

【讨论】:

  • dprint(group_vals(d)) 中的初始列表吗?
猜你喜欢
  • 1970-01-01
  • 2014-01-30
  • 1970-01-01
  • 2017-09-12
  • 2022-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
相关资源
最近更新 更多