[Tutor] Dictionary keys

alan.gauld@bt.com alan.gauld@bt.com
Mon Nov 4 11:50:21 2002


> I have just one question, is it very 'pythony' to use objects (class
> instances) as dictionary keys?

I wouldnm't describe it as the norm but its certainly within 
the python ethos. I'm not sure about how immutability of keys 
would work but I think its OK. Changes of state happen inside 
a dictionary inside the object so the object still holds the 
dictionary and so remains immutable - I think....

>>> class c:
...    def __init__(s,n):
...      s.n = n
...
>>> o = c(5)
>>> d = {}
>>> d[o] = 1
>>> o.n = 7
>>> d[o]
1
>>>


Yep, it seems to work OK.

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld