Python3:如何比较两个嵌套且动态的字典的数据? [英] Python3: How to compare data of two dictionaries which is nested and dynamic in nature?

查看:502
本文介绍了Python3:如何比较两个嵌套且动态的字典的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到一种方法来比较两个没有任何库的字典,但是数据是嵌套的,键也不是有序的.数据本质上是动态的,这意味着字典中的键也会改变和嵌套. 如果嵌套不固定,我将无法解析字典.

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.

示例数据:

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

我无法理解如何解析和比较字典? 预期输出:值不同的键和值,例如列表[srcvalue,destvalue]

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"]
}

预先感谢

推荐答案

dict的内置相等运算符已经递归比较嵌套的dict值.

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

这篇关于Python3:如何比较两个嵌套且动态的字典的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆