[英]comparing keys:- list of nested dictionary
我想编写一个 function 来检查 dict1(基本字典)的键并将其与 dict2(嵌套字典列表,可以是一个或多个)的键进行比较,以便它检查强制键,然后检查可选键(如果和无论存在什么)并将差异作为列表返回。
dict1 = {"name": str, #mandatory
"details" : { #optional
"class" : str, #optional
"subjects" : { #optional
"english" : bool, #optional
"maths" : bool #optional
}
}}
dict2 = [{"name": "SK",
"details" : {
"class" : "A"}
},
{"name": "SK",
"details" : {
"class" : "A",
"subjects" :{
"english" : True,
"science" : False
}
}}]
将 dict2 与 dict1 进行比较后,预期的 output 为:-
pass #no difference in keys in 1st dictionary
["science"] #the different key in second dictionary of dict2
试试这个递归检查 function:
def compare_dict_keys(d1, d2, diff: list):
if isinstance(d2, dict):
for key, expected_value in d2.items():
try:
actual_value = d1[key]
compare_dict_keys(actual_value, expected_value, diff)
except KeyError:
diff.append(key)
else:
pass
字典 1 与字典 2
difference = []
compare_dict_keys(dict1, dict2, difference)
print(difference)
# Output: ['science']
dict2 与 dict1
difference = []
compare_dict_keys(dict2, dict1, difference)
print(difference)
# Output: ['maths']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.