繁体   English   中英

从 python 中的多个列表创建嵌套字典

[英]Create a nested dictionary from multiple lists in python

我想从包含文件系统路径的多个列表中创建一个字典。

以下是我要转换的列表的示例:

list1 = ["root_path", "Test", "Subfolder1"]
list2 = ["root_path", "Test", "Subfolder2"]
list3 = ["root_path", "Test", "Subfolder3"]
list4 = ["root_path", "Test", "Subfolder1", "Subfolder1-1"]
list5 = ["root_path", "Test", "Subfolder1", "Subfolder1-1", "Subfolder1-1-1"]
..

生成的字典应具有以下嵌套结构:

resulting_dict = {
        "root_path": {
            "Test": {
                "Subfolder1": {
                    "Subfolder1-1": {
                        "Subfolder1-1-1": {}
                    } 
                },
                "Subfolder2": {},
                "Subfolder3": {},
            }
        }
    }

发现它真的很有挑战性。 有什么帮助吗?

使用setdefault创建嵌套字典:

# put the lists in a parent list to make iteration easier
lists = [list1, list2, list3, list4, list5]

# root dictionary
res = {}
for lst in lists:
    cursor = res  # point cursor to root dictionary
    for e in lst:
        cursor = cursor.setdefault(e, {})  # set the value to empty dictionary if not already set, return the value

print(res)

Output

{'root_path': {'Test': {'Subfolder1': {'Subfolder1-1': {'Subfolder1-1-1': {}}},
                        'Subfolder2': {},
                        'Subfolder3': {}}}}

问题解决了

def mkdir(path: list, struct: dict):
    """
    recursively create directories
    """
    walker = walk(path)
    if not path: return 
    if struct == {}:
        new_dir = struct[path[0]] = {}
        return mkdir(path[1:], new_dir)
    for name, dir in struct.items():
        if name == path[0]:
            mkdir(path[1:], dir)
            break
    else:
        new_dir = struct[path[0]] = {}
        return mkdir(path[1:], new_dir)

用法

mkdir(folder_list, base_directory)

这个 function 就像魔术一样工作。 它可以嵌套数百个目录

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM