Dictionary from a list

Jan Kaliszewski zuo at chopin.edu.pl
Thu Aug 20 02:05:57 CEST 2009


19-08-2009 o 22:52:54 iu2 <israelu at elbit.co.il> wrote:

> On Aug 19, 11:39 pm, "Diez B. Roggisch" <de... at nospam.web.de> wrote:
>> iu2 schrieb:
>>
>> > Hi all,
>>
>> > I need to create a dictionary out of a list.
>>
>> > Given the list [1, 2, 3, 4, 5, 6]
>>
>> > I need the dictionary: {1:2, 3:4, 5:6}
>>
>> dict(zip(l[::2], l[1::2]))

Or (for long lists, when memory becomes expensive):

     dict(li[i:i+2] for i in xrange(0, len(li), 2))

Or probably better:

     from itertools import islice, izip
     dict(izip(islice(li, 0, None, 2), islice(li, 1, None, 2)))

Cheers,
*j

-- 
Jan Kaliszewski (zuo) <zuo at chopin.edu.pl>



More information about the Python-list mailing list