2

我有一个看起来像这样的父子字典,其中键是子节点,0 是根节点。

node[0]=[{"parms":{"meta1":"foo"},"name":"RootNoe"}]
node[1]=[{"parent":0,"data":{"parms":{"meta2":"bar"},"name":"country"} }]
node[2]=[{"parent":1,"data":{"parms":{"meta3":"baz"},"name":"day"} }]

我需要创建一个嵌套的 json 对象,如下所示:

test = {
        "params": {"parms":{"meta1":"foo"},
        "name": "RootNode", 
         "children": [ 
                     {
                     "parms":{"meta2":"bar"},
                      "name":"country",
                      "children": [
                                 {"parms":{"meta3":"baz"},
                                  "name":"day","children": []}
                                 ]
            }]  
        }

我如何在 python 中做到这一点?

4

1 回答 1

2

您可以从循环中的定义构造树。

for element in node:
    if 'parent' in element:
        if 'children' not in node[element['parent']]:
            node[element['parent']]['children'] = []
        node[element['parent']]['children'].append(element)
        del element['parent']

test = node[0]

children需要在场才能正常工作,但我希望你能明白要点。另请注意,这会修改node序列。

于 2013-03-13T10:39:22.610 回答