Python嵌套字典对比更新:匹配后删除指定记录求助
多层嵌套字典的匹配删除实现
代码实现
def remove_matching_entries(source_dict, target_dict, temp_dict): for key, value in temp_dict.items(): if key not in source_dict: continue if isinstance(value, dict): remove_matching_entries(source_dict[key], target_dict[key], value) # 若递归后子字典为空,可选择删除父键(按需启用) # if not source_dict[key]: # del source_dict[key] # del target_dict[key] else: if source_dict[key] == value: del source_dict[key] del target_dict[key] # 初始数据 A={"X":{"XX":1,"XX1":56},"Y":{"YY":2},"Z":{"ZZ":{"ZA":34,"ZB":35}}} B={"X":{"XX":2,"XX1":34},"L":{"LL":3},"Z":{"ZZ":{"ZA":31,"ZB":38}}} temp={"X":{"XX":1},"Z":{"ZZ":{"ZA":34}}} # 执行删除操作 remove_matching_entries(A, B, temp) print("处理后的A:", A) print("处理后的B:", B)
逻辑说明
- 递归遍历:通过递归函数适配多层嵌套的字典结构,确保每一层的键值对都能被遍历检查
- 匹配删除:以
temp的结构为路径,对比A对应位置的值,匹配成功则同时删除A和B中的对应键 - 可选优化:如果递归处理后子字典变为空,可以取消注释代码块,自动删除空的父字典键(示例需求中不需要此操作)
运行代码后,输出结果与预期完全一致:
处理后的A: {'X': {'XX1': 56}, 'Y': {'YY': 2}, 'Z': {'ZZ': {'ZB': 35}}} 处理后的B: {'X': {'XX1': 34}, 'L': {'LL': 3}, 'Z': {'ZZ': {'ZB': 38}}}
内容的提问来源于stack exchange,提问作者Saman
相关产品推荐
相关产品推荐

