Python:从父子值列表创建嵌套字典 [英] Python: create a nested dictionary from a list of parent child values

查看:344
本文介绍了Python:从父子值列表创建嵌套字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是输入内容:

list_child_parent= [
    #first value is child, second is parent
    (0, 1),
    (1, 3),
    (8, 7),
    (3, 6),
    (4, 3),
    (5, 3)
]

输出需要使用这些值创建嵌套的字典树.树的深度永远不会超过6层.

The output needs to create a nested dictionary tree using these values. The tree will never be more than 6 levels deep.

例如:

output_dict = {
    6: {3: {1: {0: {}}, 4: {}, 5: {}}}, 7: {8: {}}
}

我花了两天的时间来实现这一目标.我尝试编写函数来查找键在树中的位置,然后在其后添加新键,但是我无法生成可以继续超过3个级别的代码.莫名其妙,我觉得可能有一个标准库可以做到这一点.

I have spent two days trying to accomplish this. I have tried writing functions to find where the key is in the tree and then add the new key after it, but I cannot produce code that can continue more than 3 levels. It's baffling and I feel that there is probably a standard library that can do this.

我的经验水平很低.

推荐答案

不漂亮,可能不是Pythonic,但它应该可以帮助您:

Not pretty and probably not Pythonic, but it should get you going:

#!/usr/bin/env python3

def make_map(list_child_parent):
    has_parent = set()
    all_items = {}
    for child, parent in list_child_parent:
        if parent not in all_items:
            all_items[parent] = {}
        if child not in all_items:
            all_items[child] = {}
        all_items[parent][child] = all_items[child]
        has_parent.add(child)

    result = {}
    for key, value in all_items.items():
        if key not in has_parent:
            result[key] = value
    return result

if __name__ == '__main__':
    list_child_parent = [
        #first value is child, second is parent
        (0, 1),
        (1, 3),
        (8, 7),
        (3, 6),
        (4, 3),
        (5, 3)
    ]

    actual = make_map(list_child_parent)

    expected = {
        6: {
            3: {
                1: {
                    0: {}
                },
                4: {},
                5: {}
            }
        },
        7: {
            8: {}
        }
    }
    print('OK' if expected == actual else 'FAIL')

这篇关于Python:从父子值列表创建嵌套字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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