从包含路径的列表中创建嵌套字典 [英] Creating nested dictionaries from a list containing paths

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

问题描述

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

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’:{}}}}}

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

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 ?

推荐答案

类似

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': {}}}}}}

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

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