Home > Software engineering >  comparing keys of nested dictionary
comparing keys of nested dictionary

Time:11-18

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",
            "subjects" :{
                "english" : True,
                "science" : False
            }
        }}]

After comparing dict2 with dict1,The expected output is:-

["science"]    #the different key in dict2

CodePudding user response:

convert it into data frame and perform right anti-join

CodePudding user response:

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