How to use list as key of dictionary?

D

Davy

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

Davy

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)
But {L_tuple:'hello'} cause an error?

Best regards,
Davy

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

Use a tuple instead.
d = {}
d[tuple([1,2,3,4])] = 'hello world'
d

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

'hello world'

Matt
 
W

Wildemar Wildenburger

Davy said:
> 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
 
D

Duncan Booth

Wildemar Wildenburger said:
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.
 
D

Dustan

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
 
M

Michael Wronna

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
 
D

Davy

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

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

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
Use a tuple instead.
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 -
 
P

Paul McGuire

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
 
B

Boris Borcic

You could also index on the repr() of your objects, which
is an immutable str value.
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

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

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
Use a tuple instead.
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 -
 
D

Duncan Booth

Paul McGuire said:
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)
....
 
S

Steven D'Aprano

Davy said:
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


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,
Bad Things will happen.

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

Duncan Booth

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([])
( said:
make_dict_key((list,))
( said:
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.)
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))
 
S

Steven D'Aprano

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([])
( said:
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.
 
W

Wildemar Wildenburger

Duncan said:
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
 
W

Wildemar Wildenburger

Duncan said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top