即使存在键,Python dict.get(k)也不会返回任何值 [英] Python dict.get(k) returns none even though key exists
问题描述
也许我对python字典的理解不好.但这就是问题所在.
Perhaps my understanding of python's dictionary is not good. But here's the problem.
是否曾经在字典中出现 {yolk:shell} 对 ,说的是 eggs
,却是 eggs.get(卵黄)
是否可以返回 None
?
Does it ever happen that a {yolk: shell}
pair exists in the dictionary say eggs
, but a eggs.get(yolk)
can return None
?
因此,在大型代码中,我对字典执行了多个 get
操作,并且在进行某些迭代之后,我观察到了这种情况.
So, in a large code, I do multiple get
operations for a dictionary, and after certain iterations, I observe this situation.
>>> for key, value in nodehashes.items():
... print(key, nodehashes.get(key), value)
............................
...........................
<Graph.Node object at 0x00000264128C4DA0> 3309678211443697093 3309678211443697093
<Graph.Node object at 0x00000264128C4DD8> 3554035049990170053 3554035049990170053
<Graph.Node object at 0x00000264128C4E10> None -7182124040890112571 # Look at this!!
<Graph.Node object at 0x00000264128C4E48> 3268020121048950213 3268020121048950213
<Graph.Node object at 0x00000264128C4E80> -1243862058694105659 -1243862058694105659
............................
............................
乍一看,看起来像在代码中的某个地方,键被删除了,但是 nodehashes.items()
如何返回正确的键值对?我席卷了整个区域,我根本没有弹出任何项目.这怎么会发生?
At first sight, It looks like somewhere in the code, the key is deleted, but then how does nodehashes.items()
return the correct key-value pair? I swept the entire region, I am not popping an item at all. How can this happen?
我知道我自己不发布示例是错误的,但是我真的不知道从哪里开始查找代码,这些节点在开头是散列的,并且只能通过 get进行访问代码>.令人惊讶的是,甚至PyCharm的调试器也显示了键值对的存在.但是
get
返回None.因此,如果以前有人遇到过这种情况,我将不知所措.
I know it's wrong on my part not to post an example, but I really don't know where to start looking in the code, The Nodes are hashed in the beginning and they are only accessed with get
. Surprisingly, even PyCharm's debugger shows the key-value pair to exist. But the get
returns None. So if anyone else has hit upon this before, I am all ears.
def __eq__(self, other):
if (self.x == other.x) and (self.y == other.y):
return True
else:
return False
def __hash__(self):
return hash(tuple([self.x, self.y]))
推荐答案
如果对可变对象具有自定义的 __ hash __
方法,则可以重现:
You can reproduce that if you have a custom __hash__
method on mutable objects:
class A:
def __hash__(self):
return hash(self.a)
>>> a1 = A()
>>> a2 = A()
>>> a1.a = 1
>>> a2.a = 2
>>> d = {a1: 1, a2: 2}
>>> a1.a = 3
>>> d.items()
dict_items([(<__main__.A object at 0x7f1762a8b668>, 1), (<__main__.A object at 0x7f17623d76d8>, 2)])
>>> d.get(a1)
None
您会看到 d.items()
仍然可以访问两个 A
对象,但是 get
找不到了,因为 hash
值已更改.
You can see that d.items()
still has access to both A
objects, but get
can't find it anymore, because the hash
value has changed.
这篇关于即使存在键,Python dict.get(k)也不会返回任何值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!