Converting a list to a dictionary
Steve Holden
steve at holdenweb.com
Wed Mar 14 16:51:42 EDT 2007
Drew wrote:
> On Mar 14, 4:52 pm, Bruno Desthuilliers
> <bdesth.quelquech... at free.quelquepart.fr> wrote:
>
>> 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
More information about the Python-list
mailing list