我的列表中有以下项目,其格式为目录结构。
[
'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/