Python 从另一个嵌套字典创建嵌套字典
我有一个嵌套字典,其中包含按类别分组的路径,我想创建另一个具有类似结构的字典,不同的是第二个字典将包含每个路径中的文件 原始词典:Python 从另一个嵌套字典创建嵌套字典,python,Python,我有一个嵌套字典,其中包含按类别分组的路径,我想创建另一个具有类似结构的字典,不同的是第二个字典将包含每个路径中的文件 原始词典: dic_paths={ 'folder1':{'data':['C:/Users/my_user/Desktop/Insumos1','C:/Users/my_user/Desktop/Insumos2']}, 'folder2':{'other_data':{'cat1':['C:/Users/my_user/Desktop/DATOS/to_sh
dic_paths={
'folder1':{'data':['C:/Users/my_user/Desktop/Insumos1','C:/Users/my_user/Desktop/Insumos2']},
'folder2':{'other_data':{'cat1':['C:/Users/my_user/Desktop/DATOS/to_share'],
'cat2':['C:/Users/my_user/Desktop/DATOS/others']},
'other_other_data':{'f2sub-subgroup1':['C:/Users/my_user/Desktop/DATOS/graphs']}}
}
预期结果:
dic_files={
'folder1':{'data':['list of all files in two paths']},
'folder2':{'other_data':{'cat1':['list of all files'],
'cat2':['list of all files']},
'other_other_data':{'f2sub-subgroup1':['list of all files']}}
}
当前结果:
dic_files={
'folder1':'folder1',
'data':['all files in two paths'],
'folder2':'folder2',
'other_data':'other_data',
'cat1':['list of files'],
...
}
这是我正在使用的函数,我从中获取了原始函数。另外,如何在函数内部移动数据{}
,使其不会重置?谢谢你的帮助
data_dic={}
def myprint(d,data_dic):
for k, v in d.items():
if isinstance(v, dict):
data_dic[k]=k
myprint(v,data_dic)
else:
file_list=[]
for path in v:
if type(path)!=list:
for file in os.listdir(path):
if '~$' not in file:
file_list.append(file)
data_dic[k]=file_list
return data_dic
这是你可以申请的完美案例。迭代我使用的文件夹,并使用检查每个项目 代码:
from pathlib import Path
def func(data):
if isinstance(data, dict):
return {k: func(v) for k, v in data.items()} # recursion happens here
elif isinstance(data, (list, tuple, set, frozenset)):
return [str(p) for i in data for p in Path(i).iterdir() if p.is_file()]
else:
return data # alternatively you can raise an exception
用法:
dic_paths = {
'folder1': {
'data': [
'C:/Users/my_user/Desktop/Insumos1',
'C:/Users/my_user/Desktop/Insumos2'
]
},
'folder2': {
'other_data': {
'cat1': ['C:/Users/my_user/Desktop/DATOS/to_share'],
'cat2':['C:/Users/my_user/Desktop/DATOS/others']
},
'other_other_data': {
'f2sub-subgroup1': ['C:/Users/my_user/Desktop/DATOS/graphs']
}
}
}
dic_files = func(dic_paths)