Sandy
Sandy

Reputation: 3

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

Upvotes: 0

Views: 61

Answers (1)

pL3b
pL3b

Reputation: 1329

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']

Upvotes: 0

Related Questions