简体   繁体   English

比较键:- 嵌套字典列表

[英]comparing keys:- list of nested dictionary

I want to write a function that checks keys of dict1 (base dict) and compare it to keys of dict2 (list of nested dictionaries, can be one or multiple), such that it checks for the mandatory key and then optional keys(if and whatever are present) and returns the difference as a list.我想编写一个 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
            }
        }}]

After comparing dict2 with dict1,The expected output is:-将 dict2 与 dict1 进行比较后,预期的 output 为:-

pass          #no difference in keys in 1st dictionary
["science"]    #the different key in second dictionary of dict2

Try out this recursive check function:试试这个递归检查 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

dict1 vs dict2字典 1 与字典 2

difference = []
compare_dict_keys(dict1, dict2, difference)
print(difference)

# Output: ['science']

dict2 vs dict1 dict2 与 dict1

difference = []
compare_dict_keys(dict2, dict1, difference)
print(difference)

# Output: ['maths']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM