tags:

views:

45

answers:

1

I have a list [5, 90, 23, 12, 34, 89] etc where every two values should be a (ranked) list in the dictionary.

So the list above would become {1: [5, 90], 2: [23, 12], 3: [34, 89]} etc. I've gotten close with list comprehension but haven't cracked it. I tried:

my_list = [5, 90, 23, 12, 34, 89]
my_dict = dict((i+1, [my_list[i], my_list[i+1]]) for i in xrange(0, len(my_list)/2))

Which works for the first key, but all following values are off by one index. How would you do this?

+6  A: 

You left a multiple of 2:

dict( (i+1, my_list[2*i : 2*i+2]) for i in xrange(0, len(my_list)/2) )
#                   ^

BTW, you could do this instead (with Python ≥2.6 or Python ≥3.0):

>>> it = iter(my_list)
>>> dict(enumerate(zip(it, it), start=1))
{1: (5, 90), 2: (23, 12), 3: (34, 89)}

(of course, remember to use itertools.izip instead of zip in Python 2.x)

KennyTM
Perfect, thank you. Is there an advantage to the iter approach?
Ian
IMHO, the second approach is more Pythonic, but suffers in readability when read by someone not familiar with Python. But it's still pretty cool.
Jesse Dhillon