Thoughts about Python

Greg Ewing (using wmwd2zz02 at
Wed Feb 25 02:27:14 CET 2004

Marco Aschwanden wrote:
> I know that tuples can be used as keys... but how many times do
> you need tuples as dictionary keys (it would be simple to turn a list
> into an immutable string if really needed ("::".join(["a","b"]).

Having used other languages where dictionary keys have to
be strings, I very much like the fact that I *don't* have to
do this in Python. Uniquely deriving a string from a non-flat
data structure is fraught with difficulties (e.g. in your example,
what if one of the list elements contains "::"? Or what if you
wanted to stringify [42, "elephant", myFunkyClassInstance]?) You
end up having to carefully design a stringifying scheme for each
particular case. It's a big can of hassles that I can do without.

And using a tuple as a dict key is a more common thing to do than
you might think. It synergises with another feature of the Python
syntax, that commas (and not parentheses) are what generate tuples,
to give a very nice way of using a dict as a multi-dimensional table:

    my_sparse_matrix = {}
    my_sparse_matrix[17, 42] = 88

This works because '17, 42' is an expression yielding a
tuple, and tuples can be used as dict keys.

I hope you can see now that expecting Python programmers to
"simply" turn their lists into strings for use as dict
keys would *not* go down well in the Python community. :-)

Greg Ewing, Computer Science Dept,
University of Canterbury,	
Christchurch, New Zealand

More information about the Python-list mailing list