How to use list as key of dictionary?

Duncan Booth duncan.booth at invalid.invalid
Tue Nov 6 05:43:09 EST 2007


Paul McGuire <ptmcg at austin.rr.com> wrote:

> On Nov 6, 4:08 am, Dustan <DustanGro... at gmail.com> wrote:
>> On Nov 6, 3:58 am, Duncan Booth <duncan.bo... at invalid.invalid> wrote:
>>
>> > Wildemar Wildenburger <lasses_w... at klapptsowieso.net> wrote:
>> > > 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
>>
>> > Just don't try passing that a string or anything containing a 
string.
>>
>> Untested
>>
>> def tupleize(non_tuple):
>>      if isinstance(non_tuple, str):
>>           return non_tuple
>>      try:
>>           return tuple(tupleize(thing) for thing in non_tuple)
>>      except TypeError:
>>           # non_tuple is not iterable
>>           return non_tuple
> 
> 
>     isinstance(x,basestring)
> 
> is preferred over
> 
>     isinstance(x,str)
> 
> in case x is a unicode.

Better, just don't try passing it a recursive data structure.

>>> a = [1, 2, 3]
>>> a[1] = a
>>> a
[1, [...], 3]
>>> tupleize(a)


Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    tupleize(a)
  File "<pyshell#1>", line 5, in tupleize
    return tuple(tupleize(thing) for thing in non_tuple)
  File "<pyshell#1>", line 5, in <genexpr>
    return tuple(tupleize(thing) for thing in non_tuple)
  File "<pyshell#1>", line 5, in tupleize
    return tuple(tupleize(thing) for thing in non_tuple)
  File "<pyshell#1>", line 5, in <genexpr>
    return tuple(tupleize(thing) for thing in non_tuple)
  File "<pyshell#1>", line 5, in tupleize
    return tuple(tupleize(thing) for thing in non_tuple)
...



More information about the Python-list mailing list