473,382 Members | 1,726 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,382 software developers and data experts.

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 28694
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
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

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

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

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
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
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
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 -

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
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 -

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
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.)

--
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Julien Sagnard | last post by:
Hi all, When passing a list as default argument for a function, only one list is created for all calls. exemple: >>> def f(a=): .... a.append("x") .... print a .... >>> f()
2
by: flamesrock | last post by:
Hi, Basically, what I'm trying to do is store large amounts of data in a list or dictionary and then convert that to a custom formatted xml file. My list looks roughly like this: (d,r,p]]])...
1
by: Carl J. Van Arsdall | last post by:
Python Gurus: Let me elaborate a bit more on this question. Basically, I want to know if there is some data structure in python that maps a string function name to an address of a function or...
11
by: Stef Mientki | last post by:
If I'm not mistaken, I read somewhere that you can use function-names/references in lists and/or dictionaries, but now I can't find it anymore. The idea is to build a simulator for some kind of...
3
by: psbasha | last post by:
Hi, Is it mandatory to clear the data from the List ,Dictionary and Tuples after using it?. - PSB
10
by: mk | last post by:
Calvin Spealman wrote: Well, basically nothing except I need to remember I have to do that. Suppose one does that frequently in a program. It becomes tedious. I think I will define some helper...
2
by: Manoj | last post by:
Hello All, I am very new to python. Any help will be highly appreciated. Thanks I have a list of dictionaries: a = I would like to :
4
by: dineshv | last post by:
I want to see if there is an alternative method for fast list traversal. The code is very simple: dict_long_lists = defaultdict(list) for long_list in dict_long_lists.itervalues() for element...
2
by: =?Utf-8?B?anAybXNmdA==?= | last post by:
I'm pulling records from or database by dates, and there are multiple records for each part number. The part numbers are being stored as strings in a List in a custom Employee class: ...
1
by: sachin2 | last post by:
I am using 3 types of dictionaries. 1) Dictionary<string, string > d = new Dictionary<string, string>(); 2) Dictionary<string, List<string>> d = new Dictionary<string, List<string>>(); 3)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.