Am 02.01.2011 16:36, schrieb Octavian Rasnita:
From: "Ian Kelly"<ian.g.ke...@gmail.com>
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
The grouper-way looks nice, but I tried it and it didn't work:
from itertools import *
...
d = dict(grouper(2, l))
NameError: name 'grouper' is not defined
I use Python 2.7. Should it work with this version?
Octavian
A last one:
l = [1, 2, 3, 4, 5, 6, 7, 'a', 8, 'b']
dict((x[1],x[0]) for x in ((l.pop(),l.pop()) for x in xrange(len(l)/2)))
--
http://mail.python.org/mailman/listinfo/python-list