Python字典平等问题

Python字典平等问题,python,set,equality,Python,Set,Equality,我有一只奇怪的虫子 我有一段代码: for prev_cand in self.candidates: #loop over a list of dicts if prev_cand == cand: print "I think these are equal!" print prev_cand, cand print "and here are their IDs

我有一只奇怪的虫子

我有一段代码:

for prev_cand in self.candidates: #loop over a list of dicts
  if prev_cand == cand:
    print "I think these are equal!"
    print prev_cand, cand                                                   
    print "and here are their IDs!"                                         
    print id(prev_cand), id(cand)                                           
    print "and here are their string equalities!"                           
    print str(prev_cand) == str(cand)
结果如下:

I think these are equal!
{'H__0': 2} {'H__0': 1}
and here are their IDs!
27990448 27954960
and here are their string equalities!
False
发生了什么事?我目前正在使用一种仅使用字符串相等的变通方法,但这不是正确的做法

我在他们的信息中添加了更多的指纹:

and keys
['H__0'] ['H__0']
and type of keys
[<type 'str'>] [<type 'str'>]
and values
[2] [1]
and type of values
[<type 'instance'>] [<type 'instance'>]
和键
['H_uuu0']['H_uu0']
以及钥匙的类型
[] []
价值观
[2] [1]
和值的类型
[] []
我正在尝试制作一个小的可复制代码,但到目前为止我还不能。不过我会继续努力的。 我正在运行python 2.7.3

好的,所以我认为问题在于2和1某种程度上是“实例”类型,而不是int类型。

谢谢大家的评论

打印1和2的类实例(因为repr)是同一个实例,因此相等。基本上你可以有这样的东西:

class Test:
count = 0
def __init__(self):
    self.a = ["1","2"]
def __repr__(self):
    b = self.a[self.__class__.count]
    self.__class__.count += 1
    return b

>>> a = Test()
>>> b = a
>>> a == b
True
>>> print a, b
1 2

我假设
self.candidates
是一本字典,对吗?如果是,您正在比较键。@l19:这似乎不太可能,因为prev_cand似乎是一个字典。输出表明对象不相等。键的类型和两者的值是什么?字符串键,int值?那么你所描述的就不会发生了。在任何情况下,a都是有用的。运行
{'H_uu0':2}=={'H_u0':1}
会给出预期的
False
。你的问题显然遗漏了一些信息。能否提供这两个对象本身,以便重现问题?我猜如果你用
prev_ucand={'H_u0':2}
cand={'H_u0':1}
开始代码,这个问题将无法重现。