从包含路径的列表中创建嵌套字典

时间:2018-10-24 14:35:46

标签: python-3.x list dictionary nested

我有一个包含路径的列表。例如:

links=['main',
 'main/path1',
 'main/path1/path2',
 'main/path1/path2/path3/path4',
 'main/path1/path2/path3/path5',
 'main/path1/path2/path3/path4/path6']

我想创建一个嵌套字典来按顺序存储这些路径。预期输出:

Output = {‘main’: {‘path1’: {‘path2’: {‘path3’: {‘path4’: {‘path6’: {} }},‘path5’:{}}}}}

我是python编码(v 3. +)的新手,我无法解决它。我到达路径3后变得混乱,因为路径4(嵌套着路径6)和路径5也是如此。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

类似

tree = {}
for path in links:                # for each path
    node = tree                   # start from the very top
    for level in path.split('/'): # split the path into a list
        if level:                 # if a name is non-empty
            node = node.setdefault(level, dict())
                                  # move to the deeper level
                                  # (or create it if unexistent)

定义了links后,结果为

>>> tree
{'main': {'path1': {'path2': {'path3': {'path4': {'path6': {}}, 'path5': {}}}}}}