[Tutor] Dictionary keys

Magnus Lycka magnus@thinkware.se
Mon Nov 4 07:28:01 2002


>----- Original Message -----
>From: "Simon Wittber (Maptek)" <Simon.Wittber@perth.maptek.com.au>
>
> >I have just one question, is it very 'pythony' to use objects (class
> >instances) as dictionary keys?

At 11:51 2002-11-04 +0000, Gon=E7alo Rodrigues wrote:
>Yup very Pythonesque. People do that every time.
>
>There are two things that you have to make sure, though. The class has t=
o
>define a __hash__ method - computing what is called the hsh value - and =
it
>must be so defined in such a way that if two instances are equal then th=
eir
>hash values must be the same.

Actually, you don't have to define a __hash__() method. See below.
If you don't, the object identity will be used. But note that the
object identity is actually the objects location in memory. This
means that two objects with exactly the same attributes won't be
the same dictionary key (which might or might not be what you want)
and that the dictionary key value won't persist from one program
execution to the next. Not so good if you store your dict in some
kind of file or database.

I fairly often use classes (not instances, but the classes themselves)
as dictionary keys.

 >>> class A:
...     pass
...
 >>> a =3D A()
 >>> id(a)
24323552
 >>> hash(a)
24323552
 >>> d =3D {a:1}



--=20
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se