编写嵌套字典键对比函数:校验必填与可选键并返回差异
嵌套字典键对比函数实现
需求说明
写一个函数,拿dict1当基准字典,对比dict2(一个或多个嵌套字典组成的列表)里的键,逻辑如下:
- 先查必填键有没有缺失(基准字典里没标可选的就是必填键)
- 再扫所有存在的可选键,找出目标字典里有但基准字典没有的键
- 最后把
dict2里每个字典的差异键以列表返回,没差异就返回"pass"
示例代码
# 基准字典:注释标了optional的是可选键,没标的是必填键 dict1 = { "name": str, # 必填 "details" : { # 可选 "class" : str, # 可选 "subjects" : { # 可选 "english" : bool, # 可选 "maths" : bool # 可选 } } } # 待对比的字典列表 dict2 = [ {"name": "SK", "details" : { "class" : "A" } }, {"name": "SK", "details" : { "class" : "A", "subjects" :{ "english" : True, "science" : False } } } ]
预期输出
pass # 第一个字典无键差异 ["science"] # 第二个字典存在差异键
函数实现
def compare_dict_keys(base_dict, target_list): def check_nested(base, target): # 提取当前基准层级的必填键(示例靠注释判断,实际建议用更靠谱的标记方式) base_required = [] for k, v in base.items(): # 这里简单通过值的文档字符串判断是否为可选,实际可改成元组存(类型, 是否必填) if isinstance(v, type) and "optional" not in (v.__doc__ or ""): base_required.append(k) # 检查必填键是否缺失 missing_required = [k for k in base_required if k not in target] if missing_required: return missing_required # 收集当前层级多出来的键 extra_keys = [k for k in target if k not in base] # 递归处理嵌套字典 for key in target: if key in base and isinstance(base[key], dict) and isinstance(target[key], dict): nested_extra = check_nested(base[key], target[key]) if nested_extra != "pass": extra_keys.extend(nested_extra) return extra_keys if extra_keys else "pass" # 遍历每个待对比字典,生成结果 return [check_nested(base_dict, item) for item in target_list] # 测试执行 if __name__ == "__main__": results = compare_dict_keys(dict1, dict2) for res in results: print(res)
代码说明
- 用递归函数
check_nested处理多层嵌套字典,不用重复写层级判断的代码 - 必填键判断:示例里靠注释区分,实际生产环境建议把基准字典改成
{"name": (str, True), "details": ({...}, False)}这种格式,直接把必填标记存在数据里,比读注释靠谱 - 先查必填项缺不缺,缺的直接返回;再找目标字典里多出来的键,包括嵌套层的
- 每个待对比字典的结果,没差异就返回
"pass",有差异就把多余的键列出来
内容的提问来源于stack exchange,提问作者Sandy
相关产品推荐
相关产品推荐

