如何从带有parent

编程入门 行业动态 更新时间:2024-10-07 02:29:23
本文介绍了如何从带有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

本文发布于:2023-10-23 02:32:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1519480.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:parent

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!