[英]How to recreate the tree organization in nested dictionnaries
I've a problem I have been struggling on for some time now.我有一个问题,我一直在努力解决一段时间。 What I need to do is to check things for a large amount of data inside many folders.
我需要做的是检查许多文件夹中的大量数据。 To keep track of what has been done I wanted to create a yaml file containing the tree organization of my data structure.
为了跟踪所做的事情,我想创建一个 yaml 文件,其中包含我的数据结构的树组织。 Thus, the objective is to create nested dictionaries of the folders containing data.
因此,目标是创建包含数据的文件夹的嵌套字典。 The script I made is working, but it duplicates each folder and I don't know how to call recursively the function to avoid this.
我制作的脚本正在运行,但它会复制每个文件夹,我不知道如何递归调用 function 来避免这种情况。 Here is the code:
这是代码:
def load_tree_structure_as_dictionnary(current_dict):
for dir_name in current_dict.keys():
lst_sub_dir = [f.path for f in os.scandir(dir_name) if f.is_dir()]
if lst_sub_dir == []:
current_dict[dir_name]['correct_calibration'] = None
else:
for sub_dir in lst_sub_dir:
current_dict[dir_name][sub_dir] = load_tree_structure_as_dictionnary( {sub_dir: {}} )
return current_dict
init_dict = {data_path : {} }
full_dict = load_tree_structure_as_dictionnary(init_dict)
I know the error is in the recursive call, but I can't create a new 'sub_dir' key if there isnt a dictionnary initialized ( hence the {sub_dir: {}} ) Also I am new to writing stackoverflow questions, lmk if something needs to be improved in the syntax.我知道错误出在递归调用中,但如果没有初始化的字典(因此 {sub_dir: {}} )我无法创建新的“sub_dir”键需要在语法上进行改进。
After changing current_dict[dir_name][sub_dir] = load_tree_structure_as_dictionnary( {sub_dir: {}} )
to current_dict[dir_name].update(load_tree_structure_as_dictionnary( {sub_dir: {}} ))
your code will not duplicate the sub_dir.将
current_dict[dir_name][sub_dir] = load_tree_structure_as_dictionnary( {sub_dir: {}} )
更改为current_dict[dir_name].update(load_tree_structure_as_dictionnary( {sub_dir: {}} ))
您的代码将不会复制 sub_dir。
def load_tree_structure_as_dictionnary(current_dict):
for dir_name in current_dict.keys():
lst_sub_dir = [f.path for f in os.scandir(dir_name) if f.is_dir()]
if lst_sub_dir == []:
current_dict[dir_name]['correct_calibration'] = None
else:
for sub_dir in lst_sub_dir:
current_dict[dir_name].update(load_tree_structure_as_dictionnary( {sub_dir: {}} ))
return current_dict
init_dict = {"venv" : {} }
full_dict = load_tree_structure_as_dictionnary(init_dict)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.