How to make a dict from n’th indices of tuples in list

You want something like the following:

d = {x[:2]:'item'+str(i+1) for i, x in enumerate(my_list)}

I’m going to break down how this works so it’s less “python voodoo” in the future:

Firstly, we want the first two values from each tuple in the list. This is done by list slicing: x[:2]. This says “give me the first two values of x“.

Secondly, utilize enumerate, which effectively zips our return values with a 0-based index. For example, if we called enumerate on the original list:

>>> for enum in enumerate(my_list): 
        print(enum)

(0, (1, 2, 3, 4))
(1, (5, 6, 7, 8))

This gives us back a tuple with an index as the first element and whatever was in the list in the second element.

We can unpack a two element tuple by assigning it to two values:

>>> for i, x in enumerate(my_list):
        print(str(i) + " : " + str(x))

0 : (1, 2, 3, 4)
1 : (5, 6, 7, 8)

Finally, all we need to do is put this all into a dictionary comprehension (which is very similar to a list comprehension), and do some string conversions.

Leave a Comment