简体   繁体   中英

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.

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:-

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

Try out this recursive check 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

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

# Output: ['science']

dict2 vs dict1

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

# Output: ['maths']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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