I want to create a single dictionary from multiple lists containing filesystem paths.
Here are examples for the lists I want to convert:
list1 = ["root_path", "Test", "Subfolder1"]
list2 = ["root_path", "Test", "Subfolder2"]
list3 = ["root_path", "Test", "Subfolder3"]
list4 = ["root_path", "Test", "Subfolder1", "Subfolder1-1"]
list5 = ["root_path", "Test", "Subfolder1", "Subfolder1-1", "Subfolder1-1-1"]
..
The resulting dictionary should have this nested structure:
resulting_dict = {
"root_path": {
"Test": {
"Subfolder1": {
"Subfolder1-1": {
"Subfolder1-1-1": {}
}
},
"Subfolder2": {},
"Subfolder3": {},
}
}
}
Finding it really challenging. Any help?
CodePudding user response:
Use setdefault
to create the nested dictionaries:
# put the lists in a parent list to make iteration easier
lists = [list1, list2, list3, list4, list5]
# root dictionary
res = {}
for lst in lists:
cursor = res # point cursor to root dictionary
for e in lst:
cursor = cursor.setdefault(e, {}) # set the value to empty dictionary if not already set, return the value
print(res)
Output
{'root_path': {'Test': {'Subfolder1': {'Subfolder1-1': {'Subfolder1-1-1': {}}},
'Subfolder2': {},
'Subfolder3': {}}}}
CodePudding user response:
Problem solved
def mkdir(path: list, struct: dict):
"""
recursively create directories
"""
walker = walk(path)
if not path: return
if struct == {}:
new_dir = struct[path[0]] = {}
return mkdir(path[1:], new_dir)
for name, dir in struct.items():
if name == path[0]:
mkdir(path[1:], dir)
break
else:
new_dir = struct[path[0]] = {}
return mkdir(path[1:], new_dir)
USAGE
mkdir(folder_list, base_directory)
This function works like magic! It can nest hundreds of directories.