Converting a list to a dictionary

Samuel knipknap at gmail.com
Wed Mar 14 21:43:36 CET 2007


On Mar 14, 9:32 pm, "Drew" <olso... at gmail.com> wrote:
> 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




More information about the Python-list mailing list