list 2 dict?

Hrvoje Niksic hniksic at xemacs.org
Sun Jan 2 09:38:10 EST 2011


"Octavian Rasnita" <orasnita at gmail.com> writes:

> 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'}

it = iter(l)
d = dict(izip(it, it))

izip is the iterator equivalent of zip, import it from itertools.  (Or, if
your list is short, just use zip instead.)

It can be written in a single short line, at the cost of additional
obfuscation:

d = dict(izip(*[iter(l)]*2))



More information about the Python-list mailing list