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

Parsing list of directories into nested dictionary

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

[
    '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)

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

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

你可以这样尝试,不使用递归,而是使用 *-解包将项目分离到文件(或 '')和通向该文件的路径,并使用 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': {}}}