Can python create a dictionary from a list comprehension?
Pierre Quentel
quentel.pierre at wanadoo.fr
Sun May 27 17:07:38 EDT 2007
On 27 mai, 22:55, erikcw <erikwickst... at gmail.com> wrote:
> 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
entries = dict([ (int(d.date.strftime('%m')),d.id) for d in links] )
With Python2.4 and above you can use a "generator expression"
entries = dict( (int(d.date.strftime('%m')),d.id) for d in links )
Regards,
Pierre
More information about the Python-list
mailing list