Python3: How to compare data of two dictionaries which is nested and dynamic in nature?

匆匆过客 提交于 2020-01-03 06:38:09

问题


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


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/52473178/python3-how-to-compare-data-of-two-dictionaries-which-is-nested-and-dynamic-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!