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

Paul Rubin http
Tue Sep 15 07:58:30 EDT 2009


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.



More information about the Python-list mailing list