473,545 Members | 2,113 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 28703
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...@gmai l.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...@gmai l.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#SECT ION007500000000 000000000>
and <URL:http://docs.python.org/lib/typesmapping.ht ml>.

maybe something like this could help:

def tupleize(non_tu ple):
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*********@kl apptsowieso.net wrote:
maybe something like this could help:

def tupleize(non_tu ple):
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...@i nvalid.invalidw rote:
Wildemar Wildenburger <lasses_w...@kl apptsowieso.net wrote:
maybe something like this could help:
def tupleize(non_tu ple):
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_tu ple):
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...@gmai l.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_tup le = ([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...@gmai l.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...@g mail.comwrote:
On Nov 6, 3:58 am, Duncan Booth <duncan.bo...@i nvalid.invalidw rote:
Wildemar Wildenburger <lasses_w...@kl apptsowieso.net wrote:
maybe something like this could help:
def tupleize(non_tu ple):
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_tu ple):
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,ba sestring)

is preferred over

isinstance(x,st r)

in case x is a unicode.

-- Paul

Nov 6 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
1349
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
2476
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]]]) My question is, would it be faster to use a dictionary if the elements
1
1246
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 something to that nature. If this is confusing, let me describe what I want to do and see if anyone has any ideas. basically we have:
11
1611
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 micro controller (just as a general practise, I expect it too be very slow ;-). opcodes ={ 1: ('MOV', function1, ...), 2: ('ADD', function2, ),
3
2019
by: psbasha | last post by:
Hi, Is it mandatory to clear the data from the List ,Dictionary and Tuples after using it?. - PSB
10
1477
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 function then: .... fundict = newfun ....
2
1116
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
2413
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 in long_list: array_a = m + n + p # m,n,p are variable numbers The long_list's are read from a defaultdict(list) dictionary and so
2
3204
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: List<stringParts = new List<string>(); If a part number is not already in the list, a new entry is created for an employee that gets credited this part...
1
2268
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) Dictionary<string, Dictionary<string, string>> d = new Dictionary<string, Dictionary<string, string>>(); Now I am using GetDictionaryType Function...
0
7401
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7808
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7757
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5972
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5329
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3450
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3443
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1014
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
704
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.