473,378 Members | 1,401 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,378 software developers and data experts.

Converting a list to a dictionary

Hi,

is there a short version for this?

res_dict = {}
for resource in res_list:
res_dict[resource.get_id()] = resource

This does not work:

res_dict = dict([r.get_id(), r for r in res_list])

-Samuel

Mar 14 '07 #1
9 2332
Samuel a écrit :
Hi,

is there a short version for this?

res_dict = {}
for resource in res_list:
res_dict[resource.get_id()] = resource

This does not work:

res_dict = dict([r.get_id(), r for r in res_list])
res_dict = dict((r.get_id(), r) for r in res_list)

or if you have to be compatible with older python versions:

res_dict = dict([(r.get_id(), r) for r in res_list])

HTH
Mar 14 '07 #2
Samuel wrote:
This does not work:

res_dict = dict([r.get_id(), r for r in res_list])
This does:

res_dict = dict([(r.get_id(), r) for r in res_list])
Mar 14 '07 #3
On Mar 14, 9:52 pm, Bruno Desthuilliers
<bdesth.quelquech...@free.quelquepart.frwrote:
res_dict = dict((r.get_id(), r) for r in res_list)

or if you have to be compatible with older python versions:

res_dict = dict([(r.get_id(), r) for r in res_list])
Yep, that works. Strange, I was sure I had tested the latter, but I
must have been doing something wrong.

Thanks for your help!

-Samuel

Mar 14 '07 #4
On Mar 14, 4:52 pm, Bruno Desthuilliers
<bdesth.quelquech...@free.quelquepart.frwrote:
res_dict = dict((r.get_id(), r) for r in res_list)
I'm using Python2.5 and it seems that this only gives me a hash with
the first id and first record. Am I doing something wrong?
>>class Person():
.... def __init__(self):
.... self.id = 5
....
>>mylist = []
for i in range(100):
.... mylist.append(Person())
....
>>mydict = dict((r.id,r) for r in mylist)
mydict
{5: <__main__.Person instance at 0x00A99EE0>}
>>>
Mar 14 '07 #5
On Mar 14, 9:32 pm, "Drew" <olso...@gmail.comwrote:
I'm using Python2.5 and it seems that this only gives me a hash with
the first id and first record. Am I doing something wrong?
Try this instead:
>>class Person():
.... def __init__(self):
.... self.id = 5
....
>>mylist = []
for i in range(100):
.... p = Person()
.... p.id = i
.... mylist.append(p)
....
>>mydict = dict((r.id,r) for r in mylist)
mydict
What this does is it maps the id to the object. In your case, you only
have one id.

-Samuel

Mar 14 '07 #6
On Mar 14, 4:43 pm, "Samuel" <knipk...@gmail.comwrote:
What this does is it maps the id to the object. In your case, you only
have one id.

-Samuel
This is interesting behavior, but may not be what the original poster
intended. If I understand correctly, this means that if more than one
object shares the same id, only one copy will be created in the dict.
Is this correct?

Mar 14 '07 #7
On Mar 14, 9:48 pm, "Drew" <olso...@gmail.comwrote:
This is interesting behavior, but may not be what the original poster
intended.
I am the original poster :).
If I understand correctly, this means that if more than one
object shares the same id, only one copy will be created in the dict.
Is this correct?
Yes. Dictionaries are just hashes; you can't have the same key twice.

Bye,
-Sam

Mar 14 '07 #8
Drew wrote:
On Mar 14, 4:52 pm, Bruno Desthuilliers
<bdesth.quelquech...@free.quelquepart.frwrote:
>res_dict = dict((r.get_id(), r) for r in res_list)

I'm using Python2.5 and it seems that this only gives me a hash with
the first id and first record. Am I doing something wrong?
>>>class Person():
... def __init__(self):
... self.id = 5
...
>>>mylist = []
for i in range(100):
... mylist.append(Person())
...
>>>mydict = dict((r.id,r) for r in mylist)
mydict
{5: <__main__.Person instance at 0x00A99EE0>}
Well, you aren't actually using the object's id() value as the dict key,
but the value of its id attribute. Since all the instances you create
have the same value for that attribute each change to the dict (except
the first) overwrites the immediately preceding change - you can't have
100 values in a dict all with the same key!

Try:
>>mydict = dict((id(r), r) for r in mylist)
and you'll find you then get a dict with 100 elements.

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Blog of Note: http://holdenweb.blogspot.com
See you at PyCon? http://us.pycon.org/TX2007

Mar 14 '07 #9
On Mar 14, 4:52 pm, "Samuel" <knipk...@gmail.comwrote:
On Mar 14, 9:48 pm, "Drew" <olso...@gmail.comwrote:
This is interesting behavior, but may not be what the original poster
intended.

I am the original poster :).
If I understand correctly, this means that if more than one
object shares the same id, only one copy will be created in the dict.
Is this correct?

Yes. Dictionaries are just hashes; you can't have the same key twice.

Bye,
-Sam
Doh! *Hangs head in shame and walks away slowly...* Thanks for you
gracious response :)

Mar 14 '07 #10

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

Similar topics

8
by: Robert Oschler | last post by:
Has anybody seen a Python module that will take an XML document (not a colossal one), and convert it to a Python nested class object? I'm basically looking for something that would allow me to...
9
by: Terry | last post by:
I am converting (attempting) some vb6 code that makes vast use of interfaces. One of the major uses is to be able to split out Read-only access to an obect. Let me give you a simple (contrived)...
11
by: Girish Sahani | last post by:
I wrote the following code to concatenate every 2 keys of a dictionary and their corresponding values. e.g if i have tiDict1 = tiDict1 = {'a':,'b':} i should get tiDict2={'ab':} and similarly for...
6
by: buzzweetman | last post by:
Many times I have a Dictionary<string, SomeTypeand need to get the list of keys out of it as a List<string>, to pass to a another method that expects a List<string>. I often do the following: ...
1
by: rieh25 | last post by:
If I have a dictionary such as: d = {'a' : 1, 'b' : 2} is there a way to convert it into an object o, such as: o.a = 1 o.b = 2 thanks
20
by: Gustaf | last post by:
This is two questions in one really. First, I wonder how to convert the values in a Dictionary to an array. Here's the dictionary: private Dictionary<Uri, Schemaschemas = new Dictionary<Uri,...
10
by: Frank Rizzo | last post by:
Given the inneficiencies of ArrayList and Hashtable on 64-bit systems, I am converting them to List<and Dictionary<respectively. It's a pretty massive system, so there are a lot of casts. For...
11
by: Louis.Soninhu | last post by:
Hi pals I have a list like this mylist= I'd like to remove the first and the last item as they are irrevalent, and convert it to the dict: {'tom':'boss','mike':'manager','paul':'employee'}
0
by: Gabriel Genellina | last post by:
En Fri, 19 Sep 2008 10:59:26 -0300, Ron Brennan <brennan.ron@gmail.com> escribió: I guess you probably tried using ' '.join(value) and got an error like this: TypeError: sequence item 0:...
12
by: =?Utf-8?B?THVpZ2k=?= | last post by:
Hi all, I have a dictionary like this: Dictionary<List<string>, List<string>> How can I iterate in it? Thanks very much. -- Luigi
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
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
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: 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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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.