如何用递归方法更新Python字典,构造zeep SOAP请求嵌套参数
递归实现方案
我们可以拆分两个核心逻辑:递归查找包含父参数的字典对象、复用你已经写好的更新逻辑,不需要硬编码层级判断,支持任意深度的嵌套结构。
完整实现代码
def _prepare_request_dictionary(self): data_dictionary = {} # 递归查找父参数所在的字典 def find_parent_dict(current_dict, parent_name): # 先检查当前层级有没有目标父参数 if parent_name in current_dict: return current_dict # 遍历当前层级的所有值,是字典的话就递归往下找 for value in current_dict.values(): if isinstance(value, dict): res = find_parent_dict(value, parent_name) if res is not None: return res # 没找到返回None return None # 复用原有更新逻辑 def update_parent_node(parent_dict, parent_name, child_name, child_value): update_data = {child_name: child_value} if isinstance(parent_dict[parent_name], dict): parent_dict[parent_name] = {**parent_dict[parent_name], **update_data} elif isinstance(parent_dict[parent_name], list): parent_dict[parent_name].append(update_data) elif parent_dict[parent_name] is False: parent_dict[parent_name] = update_data # 按层级顺序处理所有参数 for line in self.request_line_ids.sorted(key=lambda l: l.parameter_id.level): parameter_name = line.parameter_id.name parent_param = line.parameter_id.parent_id line_value = convert_value(line.value, line.parameter_type) if not line.parameter_id.is_compound and line.value else False # 处理根节点(level=1,没有父节点) if not parent_param: if parameter_name not in data_dictionary: data_dictionary[parameter_name] = line_value continue # 非根节点,找父节点所在的字典 parent_name = parent_param.name parent_dict = find_parent_dict(data_dictionary, parent_name) if parent_dict is None: # 按层级顺序处理不会出现父节点不存在的情况,可按需加异常处理 continue # 更新父节点 update_parent_node(parent_dict, parent_name, parameter_name, line_value) return data_dictionary
逻辑说明
- 递归查找逻辑:
find_parent_dict从根字典开始逐层遍历,只要找到包含父参数名的字典就直接返回,不需要关心当前是第几层,天然支持无限深度的嵌套结构。 - 顺序处理保证:因为你已经按
level从小到大排序参数,处理子节点时父节点一定已经被写入字典,不会出现找不到父节点的情况。 - 兼容原有逻辑:完全复用了你之前写的节点更新规则,和原有实现的输出结果完全一致,不需要修改其他业务逻辑。
测试验证
你提到的两个测试用例都可以完美支持:
- 只有par1-par4的场景,输出为
{'par0': {'par1': {'par2': {'par3': {'par4': False}}}}} - 新增par2.1作为par1子节点的场景,输出为
{'par0': {'par1': {'par2.1': False, 'par2': {'par3': {'par4': False}}}}}
内容的提问来源于stack exchange,提问作者Simon Capriles
相关产品推荐
相关产品推荐

