简体   繁体   中英

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]}

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]}

It'll work

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

output_dict = {}
for index, data in enumerate(tuple_list):
    output_dict[index] = list(data)

print(output_dict)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM