python建筑树从dicts列表

时间:2014-01-27 20:13:30

标签: python algorithm dictionary

我有一个dicts列表(dicts是有序的):

[
    OrderedDict([('id_1', '1'), ('name_1', 'name_1'), ('id_2', '1'), ('name_2', 'name_1'), ('id_3', '1'), ('name_3', 'name_1'), ('id_4', '1'), ('name_4', '1')]),
    OrderedDict([('id_1', '2'), ('name_1', 'name_2'), ('id_2', '1'), ('name_2', 'name_1'), ('id_3', '1'), ('name_3', 'name_1'), ('id_4', '1'), ('name_4', '1')]),
    ...
    ...
    ...
    OrderedDict([('id_1', 'n'), ('name_1', 'name_n'), ('id_2', 'n'), ('name_2', 'name_n'), ('id_3', 'n'), ('name_3', 'name_n'), ('id_4', 'n'), ('name_4', 'n')])
]

我认为它像桌子一样。 那么如何“建立一个查询”来构建一个像:

的树
[
    OrderedDict([('id_1', 'n'), ('name_1', 'name_n'), (
        'children', [
            OrderedDict([('id_2', 'name_2'), ('children', [
                OrderedDict([('id_3', 'name_3'), ('children', [])]),
                OrderedDict([('id_6', 'name_6'), ('children', [])]),
                ...
                ...
                OrderedDict([('id_100500', 'name_100500'), ('children', [])]),
            ])]),
            OrderedDict([('id_n', 'name_n'), ('children', [])])
        ])
    ])
]

我怎么能只用1次迭代呢?

编辑:

我在每个词典中都有关系。我有对(id和name)first - parent,然后是它的孩子,所以在第一个dict - 4 id's:

  • a = {'id_1':'1','name_1':'name_1'}

  • b = {'id_2':'1','name_2':'name_1'}

  • c = {'id_3':'1','name_3':'name_1'}

  • d = {'id_4':'1','name_4':'1'}

所以,在这里:

* a - parent
* b - child a
* c - child b
* d - child c

0 个答案:

没有答案