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:
class x(object): ... pass ... >>> x1 = x() >>> x1.prop = 'a' >>> d = {} >>> d[x1] = 'x1' >>> for i in d.iteritems(): ... if i[0].prop == 'a': ... print i ... (<__main__.x object at 0x011AC330>, 'x1') >>> x1.prop = 'b' >>> for i in d.iteritems(): ... if i[0].prop == 'b': ... print i ... (<__main__.x object at 0x011AC330>, 'x1')
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?
-- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- -- http://mail.python.org/mailman/listinfo/python-list