lists and tuples

Fredrik Lundh fredrik at pythonware.com
Sat Jun 28 09:56:16 EDT 2003


Gerrit Holl wrote:

> This is probably a basic question, but I can't see why mutable
> objects can't be used as dictionairy keys. Why would this be
> impossible:
>
>   0 >>> d = {}
>   1 >>> l = []
>   2 >>> d[l] = "foo"
>   3 >>> d
> {[]: 'foo'}
>   4 >>> l.append("bar")
>   5 >>> l
> ['bar']
>   6 >>> d
> {['bar']: 'foo'}
>
> What is the problem of doing this?

it's explained in the Python language reference:

    The only types of values not acceptable as keys are values
    containing lists or dictionaries or other mutable types that
    are compared by value rather than by object identity, the
    reason being that the efficient implementation of dictionaries
    requires a key's hash value to remain constant.

(anyone thinking of following up with "but use a tree" or "make all
objects observable" etc should check the archives first (or write
their own Python-compatible-but-slower language, and compete
in the marketplace...))

</F>








More information about the Python-list mailing list