OJAS JUNEJA OJAS JUNEJA -4 years ago 63
Python Question

Adding objects as keys in Dictionary

I am using a object as key and number as value but getting the below error in line. Any help ?


dict[a] = 1


:

Traceback (most recent call last):
File "detect_hung_connections.py", line 24, in <module>
dict = {a:1}
TypeError: __hash__() takes exactly 3 arguments (1 given)


My Code is as follows:

class A:
def __init__(self,a,b):
self.a = a
self.b = b

def __hash__(self,a,b):
return hash(self.a,self.b)

def __eq__(self,other):
return (self.a,self.b) == (other.a,other.b)

dict ={}
a = A("aa","bb")

dict[a] = 1

b = A("aa","bb")

Answer Source

The signature of A.__hash__ should not take any extra arguments.

def __hash__(self):
    return hash((self.a,self.b))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download