list 2 dict?
Ian Kelly
ian.g.kelly at gmail.com
Sun Jan 2 08:37:59 EST 2011
On 1/2/2011 6:18 AM, Octavian Rasnita 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]))
d = dict(zip(l[0::2], l[1::2]))
Or, using the "grouper" function recipe from the itertools documentation:
d = dict(grouper(2, l))
Cheers,
Ian
More information about the Python-list
mailing list