0

I am trying to find a way to compare two dictionaries without any library but the data is nested and keys are not ordered too.The data is dynamic in nature meaning the the keys in dictionary will change and nesting also. I am not able to parse the dictionary if the nesting is not fixed.

Example data:

source_data = {
    "name":"Kaleigh", "username":"Kaleigh60", "email":"Kaleigh6047@gmail.com",
    "address":{
        "street":"MyahCourse","suite":"Apt.657","city":"Boyerberg","zipcode":"66413-8920",
        "geo":{"lat":"-44.6203","lng":"16.7454"}
    },
    "website":"megane.biz",
    "friends":[
        {"name":"Little-Reinger","catchPhrase":"Enhancedregionalemulation"},
        {"name":"Big-Reinger","catchPhrase":"emulation"}
    ],
    "Numbers":[1,2,3,4]
}

destination_data = {
    "name":"Kaligh", "username": "Kaleigh60", "email": "Kaleigh6047@gmail.com",
    "address":{
        "street":"GoldCourse", "suite":"Apt.657", "city":"Boyerberg",
        "zipcode":"66413-8920",
        "geo":{"lat":"-44.6203","lng":"16.7454"}
    },
    "website":"megane.biz",
    "friends":[
        {"name":"Reinger", "catchPhrase":"Enhancedregionalemulation"},
        {"name":"Big-Reinger","catchPhrase":"emulation"}
    ],
    "Numbers":[4,2,1,5]
}

I am not able to understand how can I parse the and compare the dictionary? Expected Output: keys whose value is different and values as list [srcvalue,destvalue] e.g.

{
    "friends[1].name": ["Big-Reinger", "Bigger-Reinger"],
    "name":["Kaleigh","Kaligh"],
    "Numbers[2]":[3,1],
    "Numbers[3]":[4,5],
    "friends[0].name":["Little-Reinger","Reinger"],
    "Numbers[0]":[1,4],
    "address.street":["MyahCourse","GoldCourse"]
}

Thanks in advance

smci
  • 32,567
  • 20
  • 113
  • 146

2 Answers2

0

The built-in equality operator for dict already compares nested dict values recursively.

>>> a={1:2,3:4,2:{2:4}}
>>> b={3:4,2:{2:4},1:2}
>>> a==b
True
>>> b={3:4,2:{2:3},1:2}
>>> a==b
False
>>>
blhsing
  • 91,368
  • 6
  • 71
  • 106
-1

From here

You can compare two dictionaries based on values like this:

for x_values, y_values in zip(source_data.iteritems(), destination_data.iteritems()):
        if x_values == y_values:
            # Matched
        else:
            # Not Matched
Muhammad Haseeb
  • 634
  • 5
  • 20