Search code examples
pythonlistdictionarytuplesdictionary-comprehension

How to convert list of tuples to dictionary with index as key


I’m trying to convert a list of tuples to a dictionary with the index of the list as its key.

m = [(1, 'Sports', 222), 
     (2, 'Tools', 11),
     (3, 'Clothing', 23)]

So far, I’ve tried using:

dict((i:{a,b,c}) for a,b,c in enumerate(m))

but this is not working.

My expected output is:

{0: [1, 'Sports', 222],
 1: [2, 'Tools', 11],
 2: [3, 'Clothing', 23]}

Solution

  • Use the following dictionary comprehension:

    >>> {i:list(t) for i, t in enumerate(m)}
    {0: [1, 'Sports', 222], 1: [2, 'Tools', 11], 2: [3, 'Clothing', 23]}