Creating nested dictionaries from a list containing paths

喜你入骨 提交于 2021-02-10 14:50:26

问题


I have a list containing paths. For example:

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

I want to create a nested dictionary to store these paths in order. Expected output:

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

I am new to python coding (v 3.+) and I am unable to solve it. It gets confusing after i reach path 3 as there is path 4 (with path6 nested) and path5 as well. Can someone please help ?


回答1:


Something like

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)

With links defined as above, it results in

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


来源:https://stackoverflow.com/questions/52971687/creating-nested-dictionaries-from-a-list-containing-paths

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!