如何==在python中为字典工作

时间:2015-02-21 02:30:05

标签: python dictionary

我有下面的代码,应该比较两个字典,如果它们是相同的,则什么都不做。如果它们不相等并且存在重复键,则抛出错误。如果dict2中的键不重复,请将键和值添加到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

我遇到的问题是使用==的字典比较显示为false,即使存储在字典中的对象在对象内部具有相同的值。唯一的区别是字典中对象的指针值。 ==方法不会递归检查存储在字典中的对象的相等性吗?另外,有人可以解释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

1 个答案:

答案 0 :(得分:2)

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