How to define a class that can act as dictionary key?

Christian Heimes lists at cheimes.de
Tue Sep 15 14:06:10 CEST 2009


Paul Rubin schrieb:
> Lambda <stephenhsu9 at gmail.com> writes:
>> When I run it, it says "TypeError: unhashable instance"
>>
>> It looks like I can't use the new class object as the dictionary key.
>> What should I do?
> 
> You have to add a __hash__ method.  Untested:
> 
>     def __hash__(self): return (self.term, self.doc_freq)
> 
> is probably the easiest.

The __hash__ function must return an integer:

>>> class Hash(object):
...     def __hash__(self):
...         return (1, 2)
...
>>> hash(Hash())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: an integer is required
>>> class Hash(object):
...     def __hash__(self):
...         return hash((1, 2))
...
>>> hash(Hash())
3713081631934410656


Christian




More information about the Python-list mailing list