Can python create a dictionary from a list comprehension?
Maric Michaud
maric at aristote.info
Mon May 28 04:20:55 EDT 2007
Pierre Quentel a écrit :
> 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.
...
>
> 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 )
>
You can also create dictionaries knowing only the keys the same way (ie.
a two-dimensional array) :
In [77]: dict.fromkeys((a, b) for a in range(4) for b in range(2))
Out[78]:
{(0, 0): None,
(0, 1): None,
(1, 0): None,
(1, 1): None,
(2, 0): None,
(2, 1): None,
(3, 0): None,
(3, 1): None}
More information about the Python-list
mailing list