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 16 28686
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}
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
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
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
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.
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
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
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 -
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
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 -
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)
....
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.
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))
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.
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
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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
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()
|
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]]])...
|
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...
|
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...
|
by: psbasha |
last post by:
Hi,
Is it mandatory to clear the data from the List ,Dictionary and Tuples after using it?.
- PSB
|
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...
|
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 :
|
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...
|
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:
...
|
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)...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM).
In this month's session, the creator of the excellent VBE...
|
by: DolphinDB |
last post by:
Tired of spending countless mintues downsampling your data? Look no further!
In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
|
by: Aftab Ahmad |
last post by:
Hello Experts!
I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
|
by: Aftab Ahmad |
last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below.
Dim IE As Object
Set IE =...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM).
In this month's session, we are pleased to welcome back...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM).
In this month's session, we are pleased to welcome back...
|
by: Vimpel783 |
last post by:
Hello!
Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
|
by: ArrayDB |
last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
|
by: PapaRatzi |
last post by:
Hello,
I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
| |