How to define a class that can act as dictionary key?
Lambda
stephenhsu9 at gmail.com
Tue Sep 15 07:47:57 EDT 2009
Hi,
I'd like to define a class to use it as a dictionary key:
class dict_entry:
def __init__(self, term = "", doc_freq = 0):
self.term = term
self.doc_freq = doc_freq
def __cmp__(self, entry):
return isinstance(entry, dict_entry) and cmp(self.term,
entry.term)
def __str__(self):
return term + ", " + str(docid)
And later...
entry = dict_entry(term, len(index[term]))
self.index[entry] = []
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?
More information about the Python-list
mailing list