== 如何用于 python 中的字典

how does == work for dictionaries in python

我有下面的代码应该比较两个字典,如果它们相等则什么也不做。如果它们不相等并且存在重复键,则抛出错误。如果dict2中的key不重复,将key和value添加到dict1中。

    print 'dictionary 1 is', dict1
    print 'dictionary 2 is', dict2
    if dict1 == dict2:
        pass #does nothing since the two dictionaries are the same
    else:                   

       for key, val in dict2.items():
           if dict1.__contains__(key):
               print 'the value at', key, 'is', val.write() #prints the information stored in val which is dict2[key]
              print 'the other value at', key, 'is', dict1[key].write() #prints the information stored in dict1[key]
              raise KeyError('the added keys must be unique. Key {0} is a duplicate.'\.format(key))
           else:
              dict1[key] = val

我遇到的问题是使用 == 的字典比较显示为错误,即使存储在字典中的对象在对象内部具有相同的值。唯一的区别是字典中对象的指针值。 == 方法不是递归检查字典中存储的对象是否相等吗?此外,有人可以解释字典中 python 的相等性检查行为吗?

跳过回溯的代码的读数是:

dictionary 1 is {1: <coeffs_angle.Coeffs_angle object at 0x118c7f710>, 2: <coeffs_angle.Coeffs_angle object at 0x118c7f790>, 3: <coeffs_angle.Coeffs_angle object at 0x118c7f810>, 4: <coeffs_angle.Coeffs_angle object at 0x118c7f890>, 5: <coeffs_angle.Coeffs_angle object at 0x118c7f910>, 6: <coeffs_angle.Coeffs_angle object at 0x118c7f990>}
dictionary 2 is {1: <coeffs_angle.Coeffs_angle object at 0x118e17dd0>, 2: <coeffs_angle.Coeffs_angle object at 0x118e17e50>, 3: <coeffs_angle.Coeffs_angle object at 0x118e17ed0>, 4: <coeffs_angle.Coeffs_angle object at 0x118e17f50>, 5: <coeffs_angle.Coeffs_angle object at 0x118e17fd0>, 6: <coeffs_angle.Coeffs_angle object at 0x118e24090>}
the value at 1 is 89.5 113.3
the other value at 1 is 89.5 113.3

代码在上面的读出后抛出错误。为了确认存储在字典中的对象中的信息是相同的,我将在假设没有错误的情况下列出其余的读数。

the value at 2 is 87.9 109.47
the other value at 2 is 87.9 109.47
the value at 3 is 74.5 111.4
the other value at 3 is 74.5 111.4
the value at 4 is 63.3 125.6
the other value at 4 is 63.3 125.6
the value at 5 is 126.5 123
the other value at 5 is 126.5 123
the value at 6 is 84.8 116.4
the other value at 6 is 84.8 116.4

映射的相等性比较是递归执行的。 但是,键和值本身必须支持相等比较,以免被天真地比较。这是通过 __eq__() 方法完成的,coeffs_angle.Coeffs_angle 似乎没有实现。