如何从带有parent_id的字典中创建带有子项的字典 [英] How to create dict with childrens from dict with parent_id

查看:131
本文介绍了如何从带有parent_id的字典中创建带有子项的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从此字典中获取信息:

How to get from this dict:

    cats = [
    {'parent_id': False, 'id': 1, 'title': u'All'},
    {'parent_id': False, 'id': 2, 'title': u'Toys'},
    {'parent_id': 2, 'id': 3, 'title': u'Toypads'},
    {'parent_id': 3, 'id': 4, 'title': u'Green'},
    ]

像这样吗?

cats = [
{'parent_id': False, 'id': 1, 'title': u'All'},
{'parent_id': False,
 'children': [{'parent_id': 2,
               'children': [{'parent_id': 3, 'id': 4,
                             'title': u'Green'}],
               'id': 3, 'title': u'Toypads'},
              [{'parent_id': 3, 'id': 4, 'title': u'Green'}]],
 'id': 2, 'title': u'Toys'}
]

我需要它在Jinja2中构建菜单\子菜单. 我写了一个非常糟糕的代码.这将是一个更优雅的解决方案.

I need it to build a menu\sub-menu in Jinja2. I wrote a very bad code. It would be a more elegant solution.

    q = dict(zip([i['id'] for i in cats], cats))

    from collections import defaultdict
    parent_map = defaultdict(list)

    for item in q.itervalues():
        parent_map[item['parent_id']].append(item['id'])

    def tree_level(parent):
        for item in parent_map[parent]:
            yield q[item]
            sub_items = list(tree_level(item))
            if sub_items:
                for ca in cats:
                    if ca['id'] == item:
                        cats[cats.index(ca)]['children'] = sub_items
                        for s_i in sub_items:
                            try:
                                for ca_del_child in cats:
                                    if ca_del_child['id'] == s_i['id']:
                                        del cats[cats.index(ca_del_child)]
                            except:
                                pass
                yield sub_items
    for i in list(tree_level(False)):
        pass

推荐答案

这是一个相当简洁的解决方案:

Here is a fairly concise solution:

cats = [{'parent_id': False, 'id': 1, 'title': u'All'},
        {'parent_id': False, 'id': 2, 'title': u'Toys'},
        {'parent_id': 2, 'id': 3, 'title': u'Toypads'},
        {'parent_id': 3, 'id': 4, 'title': u'Green'},]

cats_dict = dict((cat['id'], cat) for cat in cats)

for cat in cats:
    if cat['parent_id'] != False:
        parent = cats_dict[cat['parent_id']]
        parent.setdefault('children', []).append(cat)

cats = [cat for cat in cats if cat['parent_id'] == False]

请注意,通常不需要与False进行比较,但是如果您的猫的id或parent_id为0,则应在此处使用它们.在这种情况下,对于没有父母的猫,我会使用None而不是False.

Note that the comparisons to False are generally not necessary, but they should be used here in case you had a cat with 0 as its id or parent_id. In this case I would use None instead of False for a cat with no parent.

这篇关于如何从带有parent_id的字典中创建带有子项的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆