A Saxena A Saxena - 3 months ago 14
Python Question

nth item in List to dictionary python

I am trying to create a dictionary from every nth element of a list with list's original index as key. So for example:

l = [1,2,3,4,5,6,7,8,9]


Now running

dict(enumerate(l)).items()


gives me:

dict_items([(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9)])


which is what I want. However the problem begins when I want to now select every second value from l to do this, so I try

dict(enumerate(l[::2])).items()


which gives me

dict_items([(0, 1), (1, 3), (2, 5), (3, 7), (4, 9)])


but I do not want that, I want to preserve the original index when making a dictionary. What is the best way to do this?

I want the following output

dict_items([(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)])

Answer

Use itertools.islice() on the enumerate() object:

from itertools import islice

dict(islice(enumerate(l), None, None, 2)).items() 

islice() gives you a slice on any iterator; the above takes every second element:

>>> from itertools import islice
>>> l = [1,2,3,4,5,6,7,8,9]
>>> dict(islice(enumerate(l), None, None, 2)).items()
dict_items([(0, 1), (8, 9), (2, 3), (4, 5), (6, 7)])

(note that the output is as expected, but order is, as always, determined by the hash table).

Comments