将节点列表转换为python中的嵌套字典 [英] Transforming a list of nodes in to a nested dict in python

查看:67
本文介绍了将节点列表转换为python中的嵌套字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python中有一个字典,它表示一个邻接列表,我想将此列表转换为嵌套的python字典.使用 name children 键.

I have a list of dicts in python that represents an adjacency list and i want to transform this list in to a nested python dict. with name and children keys.

这是字典列表的示例,这些是列表的前10个元素.原始包含1000个元素.

This is an example of the list of dicts, those are the 10 first elements of the list. The original contains 1000 elements.

[{'id': 1, 'name': 'External sector', 'parent_id': 0},
 {'id': 3, 'name': 'Capital and financial markets', 'parent_id': 0},
 {'id': 77, 'name': 'Credit indicators', 'parent_id': 0},
 {'id': 15, 'name': 'Economic activity', 'parent_id': 0},
 {'id': 17, 'name': 'Monetary indicators', 'parent_id': 0},
 {'id': 30, 'name': 'Regional economy', 'parent_id': 0},
 {'id': 114, 'name': 'International economy', 'parent_id': 0},
 {'id': 157, 'name': 'National private financial system', 'parent_id': 0},
 {'id': 176, 'name': 'Financial Stability', 'parent_id': 0},
 {'id': 222, 'name': 'Financial Inclusion', 'parent_id': 0}]

我尝试过的事情

我在SO中找到了该功能,能够将该字典列表转换为嵌套的python字典:

What i've tried

I've found this function in SO that is able to transform this list of dicts in to a nested python dict:

def list_to_tree(data):
    out = { 
#         0: { 'id': 0, 'parent_id': 0, 'name': "Root node", 'sub': [] }
    }

    for p in data:
        out.setdefault(p['parent_id'], { 'sub': [] })
        out.setdefault(p['id'], { 'sub': [] })
        out[p['id']].update(p)
        out[p['parent_id']]['sub'].append(out[p['id']])

    return out[0]

此函数以这种方式生成字典:

This function produces dicts in this way:

{'id': 0,
 'name': 'rootnode',
 'parent_id': None,
 'sub': [{'id': 1,
          'name': 'External sector',
          'parent_id': 0,
          'sub': [{'id': 2,
                   'name': 'Exchange rates',
                   'parent_id': 1,
                   'sub': [{'id': 242,
                            'name': 'Controlled or free rates',
                            'parent_id': 2,
                            'sub': []},
                           {'id': 243,
                            'name': 'Floating rates',
                            'parent_id': 2,
                            'sub': []},
                           {'id': 532,
                            'name': 'Real and effective exchange rate indices',
                            'parent_id': 2,
                            'sub': []},
                           {'id': 533,
                            'name': 'Foreign exchange and wage indicators',
                            'parent_id': 2,
                            'sub': []},
                           {'id': 548,
                            'name': 'Average of period',
                            'parent_id': 2,
                            'sub': []},

但是我想以这种方式来制作字典,而没有ID's

But i wanted to produce dicts in this way, without the id's

{
 'name': 'rootnode',
 'children': [{
          'name': 'External sector',
          'children': [{
                   'name': 'Exchange rates',
                   'children': [{
                            'name': 'Controlled or free rates',
                            'children': []},
                           {
                            'name': 'Floating rates',
                            'children': []},
                           {
                            'name': 'Real and effective exchange rate indices',
                            'children': []},
                           {
                            'name': 'Foreign exchange and wage indicators',
                            'children': []},
                           {
                            'name': 'Average of period',
                            'children': []},

有什么办法可以更改我发现的此功能以产生所需的输出?任何提示,技巧或建议都非常受欢迎.

Is there any way that i can change this function that i've found in order to produce the desired output? Any hint, tip or advice is more than welcome.

推荐答案

您可以对函数进行一些修改:

You can use the function with slight modifications:

  • 使用儿童"键代替"sub"
  • 仅使用您想要的键(名称和子级)来初始化根节点
  • 代替调用 .update (复制所有所有键),只需分配名称"键
  • Use the 'children' key instead of 'sub'
  • Initialise the root node with only the keys you want to have (name & children)
  • Instead of calling .update (which copies all keys), assign just the 'name' key
def list_to_tree(data):
    out = { 
        0: { 'name': 'rootnode', 'children': [] }
    }

    for p in data:
        out.setdefault(p['parent_id'], { 'children': [] })
        out.setdefault(p['id'], { 'children': [] })
        out[p['id']]['name'] = p['name']
        out[p['parent_id']]['children'].append(out[p['id']])

    return out[0]

这篇关于将节点列表转换为python中的嵌套字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆