python - 将目录列表解析为嵌套字典

标签 python dictionary directory-structure

我的列表中有以下项目,其格式为目录结构。

[
    'fold/2021/',
    'fold/2021/11/',
    'fold/2021/11/01/',
    'fold/2021/11/01/123.gz',
    'fold/2021/11/01/345.gz',
    'fold/2021/12/',
    'fold/2021/12/02/',
    'fold/2022/'
]

我需要在以下嵌套字典结构中使用它:

{
  "fold": {
    "2021": {
      "11": {
        "01": {
          "123.gz": None,
          "345.gz": None
        }
      },
      "12": {
        "02": {}
      }
    },
    "2022": {}
  }
}

我尝试了很多递归和其他一些方法,但我没有得到这个结构。

这是我尝试过的:

def get_directory_structure(path):
    global main_dict

    local_dict = {}

    a = path.rstrip('/').split('/')
    local_dict.setdefault(a[0], {})

    if len(a) > 1:
        return_dict = get_directory_structure(path[path.find('/')+1:])
        
        local_dict[a[0]] = return_dict

        if a[0] == 'fold':
            main_dict.update(**local_dict)
        
    return local_dict

main_dict = {}
for path in paths:
    get_directory_structure(main_dict, path)

print(main_dict)

请帮我解决这个问题。谢谢

注意:- 我的电脑上没有该文件夹。我只有列表中的项目

最佳答案

您可以这样尝试,不使用递归,而是使用 *-unpacking 将项目分离到文件(或 '')以及通向该文件的路径中,并使用 setdefault 来“扩展”字典的更深层次(如果它们尚不存在),最后添加文件(如果有)。

res = {}
for item in lst:
    d = res
    *path, last = item.split("/")
    for p in path:
        d = d.setdefault(p, {})
    if last != "":
        d[last] = None

之后,res 应该是您想要的结果:

{'fold': {'2021': {'11': {'01': {'123.gz': None, '345.gz': None}}, '12': {'02': {}}}, '2022': {}}}

关于python - 将目录列表解析为嵌套字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69927969/

相关文章:

python - python.subprocess(cppBinaryExe) 会影响 cppBinaryExe 的性能吗?

python - 按 10 分钟间隔对 pandas DataFrame 进行分组

Python字典值基于特定键合并

python - 如果有重复的键,python 字典理解总是 "last wins"

java - "Too many open files in system"列出递归目录结构时失败

c# - 确定将代码分解到不同文件夹和命名空间的最佳方式

python - 在 python 中,如果持有锁,则暂时释放锁

javascript - 如何为大 map 创建小 map ? (HTML5-javascript)

c# - 如何将这个字符串拆分成 Dictionary<string,string>?

go - 在 go vet 之后,命名文件必须都在一个目录中;