Python:从父子值列表创建嵌套字典

Dan*_*fee 5 python treeview dictionary python-3.x

这是输入:

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

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

例如:

output_dict = {
    6: {3: {1: {0: {}}, 4: {}, 5: {}}}, 7: {8: {}}
}
Run Code Online (Sandbox Code Playgroud)

我花了两天时间试图完成这个任务。我尝试编写函数来查找键在树中的位置,然后在其后添加新键,但我无法生成可以继续超过 3 个级别的代码。这令人困惑,我觉得可能有一个标准库可以做到这一点。

我的经验水平很低。

Rus*_*ord 4

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

#!/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')
Run Code Online (Sandbox Code Playgroud)