Can python create a dictionary from a list comprehension?

Stefan Sonnenberg-Carstens stefan.sonnenberg at pythonmeister.com
Sun May 27 17:05:29 EDT 2007


erikcw schrieb:
> Hi,
>
> I'm trying to turn o list of objects into a dictionary using a list
> comprehension.
>
> Something like
>
> entries = {}
>  [entries[int(d.date.strftime('%m'))] = d.id] for d in links]
>
> I keep getting errors when I try to do it.  Is it possible?  Do
> dictionary objects have a method equivalent to [].append?  Maybe a
> lambda?
>
> Thanks for your help!
> Erik
>
>   
normally a dict(whatEver) will do ;-)

Example:

a = [1,2,3,4,5,6,7,8,9,10]

aDict = dict([(x,x+1) for x in a if x%2==0])

print aDict




More information about the Python-list mailing list