Search code examples
pythonobjectdictionarykey

Using object as key in dictionary in Python - Hash function


I am trying to use an object as the key value to a dictionary in Python. I follow the recommendations from some other posts that we need to implement 2 functions: __hash__ and __eq__

And with that, I am expecting the following to work but it didn't.

class Test:
    def __init__(self, name):
        self.name = name
        
    def __hash__(self):
        return hash(str(self.name))
        
    def __eq__(self, other):
        return str(self.name) == str(other,name)
        
        
def TestMethod():
    test_Dict = {}
    
    obj = Test('abc')
    test_Dict[obj] = obj
    
    print "%s" %(test_Dict[hash(str('abc'))].name)       # expecting this to print "abc" 

But it is giving me a key error message:

KeyError: 1453079729188098211

Solution

  • Elements of a mapping are not accessed by their hash, even though their hash is used to place them within the mapping. You must use the same value when indexing both for storage and for retrieval.