Skip to content Skip to sidebar Skip to footer

Python Dict.get(k) Returns None Even Though Key Exists

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

Solution 1:

You can reproduce that if you have a custom __hash__ method on mutable objects:

classA:
    def__hash__(self):
        returnhash(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.

Post a Comment for "Python Dict.get(k) Returns None Even Though Key Exists"