python列表、字典转树状结构


各位大神,求助
直接上代码:
现有一个列表:


 b_list = [{u'domain': u'', u'business_id': 1, u'business3': u'jetty', u'business2': u'nginx', u'business1': u'music', u'business4': u'[\u8fd0\u8425\u4e2d]', u'remarks': '', 'department_id': 1},
           {u'domain': None, u'business_id': 3, u'business3': u'php', u'business2': u'nginx', u'business1': u'app', u'business4': u'[\u5f85\u8fd0\u8425]', u'remarks': u'\u57ced', u'department_id': 1},
           {u'domain': u'dd', u'business_id': 4, u'business3': u'mysql', u'business2': u'python', u'business1': u'music', u'business4': u'll', u'remarks': u'', u'department_id': 1}]

想要转成树状结构,如:


 tree = [
           {'children': [{'business': u'music',
                'children': [{'business': u'nginx',
                    'children': [{'business': u'jetty',
                        'children': [{'business': u'[\u8fd0\u8425\u4e2d]','business_id': 1}
                                    ]
                                 }
                             ]},
                             {'business': u'python',
                                 'children': [{'business': u'mysql',
                                     'children': [{'business': u'll','business_id': 4}]
                                             }]
                             }
                          ]},
                          {'business': u'app',
                              'children': [{'business': u'php',
                                  'children': [{'business': u'jetty',
                                      'children': [{'business': u'[\u8fd0\u8425\u4e2d]','business_id': 2}]
                                               }
                                           ]}
                          ]}
                         ],
          'department': 1
        }
 ]

第一层是 'department_id'、第二层是business1、第三层是business2、第四层是business3、第五层是business4,第五层时把business_id赋值上
每一层,如果值的相同的则子节点,即children合并成一个列表。

不知道我表述清楚不,感谢!

字典 python 字典树 树状数组

烤鱼的妖婆 10 years, 1 month ago

Your Answer