Python dict.get(k) returns none even though key exists

时光总嘲笑我的痴心妄想 提交于 2021-01-27 15:31:50

问题


Perhaps my understanding of python's dictionary is not good. But here's the problem.

Does it ever happen that a {yolk: shell} pair exists in the dictionary say eggs, but a eggs.get(yolk) can return None?

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
   ............................
   ............................


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?

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]))

回答1:


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

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.



来源:https://stackoverflow.com/questions/61118043/python-dict-getk-returns-none-even-though-key-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!