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

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Tue Sep 15 08:48:17 EDT 2009


Lambda a écrit :
> Hi,
> 
> I'd like to define a class to use it as a dictionary key:
> 

Others already answered (define the __hash__ method). Just one point: 
the value returned by the __hash__ method should not change for the 
lifetime of the object. So if you use instance attributes to compute the 
hash, make sure these attributes won't change, else you may have a surprise:

 >>> class Foo(object):
...    def __init__(self, a, b):
...        self.a = a; self.b = b
...    def __hash__(self):
...        return hash((self.a, self.b))
...
 >>> f = Foo("un", "deux")
 >>> d = {f:"un deux"}
 >>> d[f]
"un deux"
 >>> f.a = "zero"
 >>> d[f]
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
KeyError: <__main__.Foo object at 0x9d04b2c>



HTH



More information about the Python-list mailing list