我有一个类似的路径和内容列表:
paths = [
("/test/file1.txt", "content1"),
("/test/file2.txt", "content2"),
("/file3.txt", "content3"),
("/test1/test2/test3/file5.txt", "content5"),
("/test2/file4.txt", "content4")
]
我会将此路径列表转换为:
structure = {
"file3.txt": "content3"
"test": {
"file1.txt": "content1",
"file2.txt": "content2"
},
"test2": {
"file4.txt": "content4"
}
}
这个问题有没有简单的解决方案?
答案 0 :(得分:0)
尝试使用递归:
paths = [
("/test/file1.txt", "content1"),
("/test/file2.txt", "content2"),
("/file3.txt", "content3"),
("/test2/file4.txt", "content4"),
('/test1/test2/test3/file.txt', 'content'),
('/test10/test20/test30/test40/file.txt', 'content100')
]
def create_structure(elems,count,mylen,p_1,var):
if mylen<=2:
var[elems[count]] = p_1
return
create_structure(elems,count+1,mylen-1,p_1,var.setdefault(elems[count],{}))
structure = {}
for p in paths:
elems = p[0].split('/')
create_structure(elems,1,len(elems),p[1],structure)
print structure
答案 1 :(得分:0)
我认为BAIL_OUT
可以:
.setdefault()
答案 2 :(得分:0)
由于文件路径可以是任意深度,因此我们需要可扩展的东西。
这是一种递归方法 - 递归地分割路径,直到我们到达根/
:
import os
paths = [
("/test/file1.txt", "content1"),
("/test/file2.txt", "content2"),
("/file3.txt", "content3"),
("/test1/test2/test3/file5.txt", "content5"),
("/test2/file4.txt", "content4")
]
def deepupdate(original, update):
for key, value in original.items():
if key not in update:
update[key] = value
elif isinstance(value, dict):
deepupdate(value, update[key])
return update
def traverse(key, value):
directory = os.path.dirname(key)
filename = os.path.basename(key)
if directory == "/":
return value if isinstance(value, dict) else {filename: value}
else:
path, directory = os.path.split(directory)
return traverse(path, {directory: {filename: value}})
result = {}
for key, value in paths:
result = deepupdate(result, traverse(key, value))
print(result)
使用此处建议的deepupdate()
function。
打印:
{'file3.txt': 'content3',
'test': {'file1.txt': 'content1', 'file2.txt': 'content2'},
'test1': {'test2': {'test3': {'file5.txt': 'content5'}}},
'test2': {'file4.txt': 'content4'}}