如何使用parent_id从dict创建带有子节点的dict

时间:2012-04-06 18:32:01

标签: python dictionary parent-child

如何摆脱这个词:

    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中构建菜单\子菜单。 我写了一个非常糟糕的代码。这将是一个更优雅的解决方案。

    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

2 个答案:

答案 0 :(得分:4)

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

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的比较通常不是必需的,但是如果您的cat为0作为其id或parent_id,则应使用它们。在这种情况下,对于没有父母的猫,我会使用None代替False

答案 1 :(得分:2)

可以按照以下方式完成:

# Step 1: index all categories by id and add an element 'children'
nodes = {}
for cat in cats:
    nodes[cat['id']] = cat
    cat['children'] = []

# Step 2: For each category, add it to the parent's children
for index, cat in nodes.items():
    if cat['parent_id']:
        nodes[cat['parent_id']]['children'].append(cat)

# Step 3: Keep only those that do not have a parent
cats = [c for c in nodes.values() if not c['parent_id']]

请注意,每个节点都有一个名为'children'的属性,该属性可以是空列表,也可以是包含一个或多个节点的列表。如果您不想要空的children列表,只需在nodes中的每个类别的步骤2和步骤之间删除它们。

另请注意,上面假设实际存在给定parent_id的节点。最后,请注意,如果存在id为零的节点,if not c['parent_id']也将成立,因此如果发生这种情况,您需要记住这一点。