How to use list as key of dictionary?

Wildemar Wildenburger lasses_weil at klapptsowieso.net
Tue Nov 6 04:46:48 EST 2007


Davy wrote:
 > Hi Matimus and Boris,
 >
 > Thank you :)
 >
 > And a further question about vector above rank 1, how can I use it as
 > the key of dictionary?
 >
 > For example, if I have list like L=[[1,2,3],[4,5,6,7]],
 > Then I do L_tuple = tuple(L)
 >>>> L_tuple = ([1,2,3],[4,5,6,7])
 > But {L_tuple:'hello'} cause an error?
 >
Yes, because your key still contains mutable elements. That should not 
surprise you. If it does, please (re-)read 
<URL:http://docs.python.org/tut/node7.html#SECTION007500000000000000000> 
and <URL:http://docs.python.org/lib/typesmapping.html>.

maybe something like this could help:

def tupleize(non_tuple):
     try:
         return tuple(tupleize(thing) for thing in non_tuple)
     except TypeError:
         # non_tuple is not iterable
         return non_tuple

/W



More information about the Python-list mailing list