繁体   English   中英

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

[英]how does == work for dictionaries in python

我下面的代码应该比较两个字典,如果它们相等,则什么也不做。 如果它们不相等并且键重复,则抛出错误。 如果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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM