objects as mutable dictionary keys

John Roth newsgroups at jhrothjr.com
Tue Dec 28 00:26:48 CET 2004

"Peter Maas" <peter at somewhere.com> wrote in message 
news:33bdosF3qm2j6U1 at individual.net...
> There was a huge and sometimes heated debate about tuples, lists and
> dictionaries recently, and the mainstream opinion was that dictionary
> keys must not be mutable, so lists are not allowed as dictionary keys.
> BUT: objects are allowed as dictionary keys, aren't they? See the
> interpreter session below:


> This strikes me because if one can do this with instances of user
> defined classes why not with lists? Trying to use lists as dict
> keys yields "TypeError: list objects are unhashable". So why are
> list objects unhashable and user defined objects hashable? For
> user defined objects hash(x1) = id(x1), why not do the same
> with lists?
> I think it's because of the existence of list literals. If you
> would use id() as a hash function for lists how should d[[1,2,3]]
> be stored? For instances of user defined classes there is no
> literal and accordingly no problem to use id() as a hash function
> and instances as dictionary keys.
> Is that correct?

No. The basic answer is that it's up to the object whether
it will allow itself to be used as a dictionary key. In other
words, if the designer of an object thinks it makes sense
for instances to be dictionary keys, then he can supply a
__hash__() method. If he doesn't, then he doesn't supply
such a method, and it won't work.

Each class gets to make its own decision. If a class
has a __hash__()  method defined, then it can be
used as a dictionary key. If it doesn't, then it can't.
There are no other constraints on the class designer;
in particular, global logical considerations simply don't
apply. It's the designer's whim, and nothing more.

The designers of the list object decided not to allow it
to be used as a dictionary key. That was their choice,
and I pretty much agree with it.

John Roth

> -- 
> -------------------------------------------------------------------
> Peter Maas,  M+R Infosysteme,  D-52070 Aachen,  Tel +49-241-93878-0
> E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64')
> ------------------------------------------------------------------- 

More information about the Python-list mailing list