Converting a list to a dictionary

Drew olsonas at gmail.com
Wed Mar 14 16:32:06 EDT 2007


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




More information about the Python-list mailing list