python3字典比较,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.

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

解决方案

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

>>>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值