[英]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.