list 2 dict?

Glazner yoavglazner at gmail.com
Mon Jan 3 05:41:23 EST 2011


On Jan 2, 3:18 pm, "Octavian Rasnita" <orasn... at gmail.com> wrote:
> Hi,
>> If I want to create a dictionary from a list, is there a better way than the long line below?
>> l = [1, 2, 3, 4, 5, 6, 7, 'a', 8, 'b']
>> d = dict(zip([l[x] for x in range(len(l)) if x %2 == 0], [l[x] for x in range(len(l)) if x %2 == 1]))
>> print(d)
>> {8: 'b', 1: 2, 3: 4, 5: 6, 7: 'a'}
>> Thanks.
>> Octavian

this is efficient
l = [1,2,3,4,5,6]
>>> dict(izip(islice(l,0,len(l),2),islice(l,1,len(l),2)))
{1: 2, 3: 4, 5: 6}


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /