471,831 Members | 1,633 Online

# How to use list as key of dictionary?

Hi all,

We know that list cannot be used as key of dictionary. So, how to work
around it?

For example, there is random list like l=[1,323,54,67].

Any suggestions are welcome!

Best regards,
Davy

Nov 6 '07 #1
16 28539
Davy wrote:
Hi all,

We know that list cannot be used as key of dictionary.
Yeah, but do we know why ?
So, how to work
around it?
That's a subsidiary question.
>
For example, there is random list like l=[1,323,54,67].
Don't use 1owercase L as a variab1e name, p1ease !
>
Any suggestions are welcome!
>>{tuple([1,323,54,67]):666}
{(1, 323, 54, 67): 666}
Nov 6 '07 #2
On Nov 5, 10:53 pm, Davy <zhushe...@gmail.comwrote:
Hi all,

We know that list cannot be used as key of dictionary. So, how to work
around it?

For example, there is random list like l=[1,323,54,67].

Any suggestions are welcome!

Best regards,
Davy
>>d = {}
d[tuple([1,2,3,4])] = 'hello world'
d
{(1, 2, 3, 4): 'hello world'}
>>d[1,2,3,4]
'hello world'

Matt

Nov 6 '07 #3
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?

Best regards,
Davy

On Nov 6, 3:09 pm, Matimus <mccre...@gmail.comwrote:
On Nov 5, 10:53 pm, Davy <zhushe...@gmail.comwrote:
Hi all,
We know that list cannot be used as key of dictionary. So, how to work
around it?
For example, there is random list like l=[1,323,54,67].
Any suggestions are welcome!
Best regards,
Davy

>d = {}
d[tuple([1,2,3,4])] = 'hello world'
d

{(1, 2, 3, 4): 'hello world'}>>d[1,2,3,4]

'hello world'

Matt

Nov 6 '07 #4
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
<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
Nov 6 '07 #5
Wildemar Wildenburger <la*********@klapptsowieso.netwrote:
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.

Nov 6 '07 #6
On Nov 6, 3:58 am, Duncan Booth <duncan.bo...@invalid.invalidwrote:
Wildemar Wildenburger <lasses_w...@klapptsowieso.netwrote:
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

Nov 6 '07 #7

On Tue, 6 Nov 2007, Boris Borcic wrote:
>We know that list cannot be used as key of dictionary.
Yeah, but do we know why ?
I think, because lists are mutable and a key of a dictionary
MUST be unmutable, not to crash the dictionary by accidently
changing one of its keys!

Mike
Nov 6 '07 #8
And there may be more complex list(vector like 3 or 4 dimentional data
structure), is there any easy method to tackle this problem?

Any suggestions are welcome!

Best regards,
Davy

On Nov 6, 4:50 pm, Davy <zhushe...@gmail.comwrote:
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?

Best regards,
Davy

On Nov 6, 3:09 pm, Matimus <mccre...@gmail.comwrote:
On Nov 5, 10:53 pm, Davy <zhushe...@gmail.comwrote:
Hi all,
We know that list cannot be used as key of dictionary. So, how to work
around it?
For example, there is random list like l=[1,323,54,67].
Any suggestions are welcome!
Best regards,
Davy
>>d = {}
>>d[tuple([1,2,3,4])] = 'hello world'
>>d
{(1, 2, 3, 4): 'hello world'}>>d[1,2,3,4]
'hello world'
Matt- Hide quoted text -

- Show quoted text -

Nov 6 '07 #9
On Nov 6, 4:08 am, Dustan <DustanGro...@gmail.comwrote:
On Nov 6, 3:58 am, Duncan Booth <duncan.bo...@invalid.invalidwrote:
Wildemar Wildenburger <lasses_w...@klapptsowieso.netwrote:
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.

-- Paul

Nov 6 '07 #10
You could also index on the repr() of your objects, which
is an immutable str value.

Davy wrote:
And there may be more complex list(vector like 3 or 4 dimentional data
structure), is there any easy method to tackle this problem?

Any suggestions are welcome!

Best regards,
Davy

On Nov 6, 4:50 pm, Davy <zhushe...@gmail.comwrote:
>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?

Best regards,
Davy

On Nov 6, 3:09 pm, Matimus <mccre...@gmail.comwrote:
>>On Nov 5, 10:53 pm, Davy <zhushe...@gmail.comwrote:
Hi all,
We know that list cannot be used as key of dictionary. So, how to work
around it?
For example, there is random list like l=[1,323,54,67].
Any suggestions are welcome!
Best regards,
Davy
>d = {}
>d[tuple([1,2,3,4])] = 'hello world'
>d
{(1, 2, 3, 4): 'hello world'}>>d[1,2,3,4]
'hello world'
Matt- Hide quoted text -
- Show quoted text -

Nov 6 '07 #11
Paul McGuire <pt***@austin.rr.comwrote:
On Nov 6, 4:08 am, Dustan <DustanGro...@gmail.comwrote:
>On Nov 6, 3:58 am, Duncan Booth <duncan.bo...@invalid.invalidwrote:
Wildemar Wildenburger <lasses_w...@klapptsowieso.netwrote:
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)
....
Nov 6 '07 #12
On Tue, 06 Nov 2007 10:46:48 +0100, Wildemar Wildenburger wrote:
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
<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

Not quite, because that will also convert strings to tuples, which may
not be what you want for a general solution.

For the specific example given, a list of lists:
list_of_lists = [[1,2,3], [2,3,4], [5,5,5]]
tuple_of_tuples = tuple([tuple(x) for x in list_of_lists])
The above solution might not scale for deeply nested data structures, or
for arbitrary lists, but it may solve the Original Poster's problem.

An *almost* completely general solution is quite involved (and probably
overkill for most practical uses):

def make_dict_key(K):
try:
hash(K)
return K
except TypeError:
# Not hashable, so can't be used as a dictionary key.
if isinstance(K, dict):
return (type(K),) + tuple(
(key, make_dict_key(value)) for (key, value) in K.iteritems())
else:
try:
return (type(K),) + tuple(make_dict_key(x) for x in K)
except TypeError:
# K is not a sequence-like object.
return (type(K), repr(K))
That works for all data types I've tried, and it insures that the keys it
makes from different types are distinguishable:

e.g.

make_dict_key([(1, 2), (3, 4)]) != make_dict_key({1: 2, 3: 4})

and it is as close to reversible as it is possible to get. However, there
is one limitation that makes it less than completely general: it doesn't
handle cycles. If the prospective key K includes a reference to itself,

(I leave fixing that limitation as an exercise for the reader.)

--
Steven.
Nov 6 '07 #13
Steven D'Aprano <st***@REMOVE-THIS-cybersource.com.auwrote:
Not quite, because that will also convert strings to tuples, which may
not be what you want for a general solution.
I take it you didn't actually try the original code then. Converting
strings to tuples is not something it did.
That works for all data types I've tried, and it insures that the keys
it makes from different types are distinguishable:

e.g.

make_dict_key([(1, 2), (3, 4)]) != make_dict_key({1: 2, 3: 4})
Really? It seems to me to be quite easy to get a clash:
>>make_dict_key([])
(<type 'list'>,)
>>make_dict_key((list,))
(<type 'list'>,)
>
and it is as close to reversible as it is possible to get. However,
there is one limitation that makes it less than completely general: it
doesn't handle cycles. If the prospective key K includes a reference
to itself, Bad Things will happen.

(I leave fixing that limitation as an exercise for the reader.)
>>marker=object()
def make_dict_key(K, ids=None):
try:
hash(K)
return K
except TypeError:
if ids is None:
ids = {}
if id(K) in ids:
return marker, ids[id(K)]
ids[id(K)] = len(ids)
# Not hashable, so can't be used as a dictionary key.
if isinstance(K, dict):
return (type(K),) + tuple(
(key, make_dict_key(value, ids)) for (key, value) in K.iteritems())
else:
try:
return (type(K),) + tuple(make_dict_key(x, ids) for x in K)
except TypeError:
# K is not a sequence-like object.
return (type(K), repr(K))

>>a = [1, 2, 3]
b = [4, 5, 6]
a[1] = b
b[1] = a
c = [1, a, b]
make_dict_key(c)
(<type 'list'>, 1, (<type 'list'>, 1, (<type 'list'>, 4,
(<object object at 0x00A30468>, 1), 6), 3), (<object object at 0x00A30468>, 2))
Nov 6 '07 #14
On Tue, 06 Nov 2007 11:25:29 +0000, Duncan Booth wrote:
Steven D'Aprano <st***@REMOVE-THIS-cybersource.com.auwrote:
>Not quite, because that will also convert strings to tuples, which may
not be what you want for a general solution.

I take it you didn't actually try the original code then.
No I didn't.
Converting strings to tuples is not something it did.
Ah yes, you're right. The old "single characters are sequences too"
gotcha bites again.

>That works for all data types I've tried, and it insures that the keys
it makes from different types are distinguishable:

e.g.

make_dict_key([(1, 2), (3, 4)]) != make_dict_key({1: 2, 3: 4})

Really? It seems to me to be quite easy to get a clash:
>>>make_dict_key([])
(<type 'list'>,)
>>>make_dict_key((list,))
(<type 'list'>,)

I should have said "tries to insure". It isn't strictly possible to avoid
all clashes, even in principle. For any mutable object M, if make_dict_key
(M) returns a key K, then make_dict_key(K) will also return K.

However, the clashes are for unusual containers with a type as the first
element, instead of "usual" containers containing lists, tuples, strings,
etc. Unless you deal with tuples with the first item being a type, you
shouldn't come across any clashes.
Also: nice work on supporting recursive data structures, thanks.
--
Steven.
Nov 6 '07 #15
Duncan Booth wrote:
Wildemar Wildenburger <la*********@klapptsowieso.netwrote:
>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.
Outch! Right you are.

We'll that's the genius of paid updates for you.

/W
Nov 7 '07 #16
Duncan Booth wrote:
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)
...
Your'e a fiend!

;)

/W
Nov 7 '07 #17

### This discussion thread is closed

Replies have been disabled for this discussion.