Python3:如何比较两个嵌套且动态的字典的数据?

时间:2018-09-24 05:32:44

标签: python python-3.x dictionary nested

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

示例数据:

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]等值,例如

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

预先感谢

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:-1)

来自here

您可以根据以下值比较两个字典:

for x_values, y_values in zip(source_data.iteritems(), destination_data.iteritems()):
        if x_values == y_values:
            # Matched
        else:
            # Not Matched