Python 如何将元组列表转换为以索引为键的字典
我正在尝试将元组列表转换为以列表索引为键的字典Python 如何将元组列表转换为以索引为键的字典,python,list,dictionary,tuples,dictionary-comprehension,Python,List,Dictionary,Tuples,Dictionary Comprehension,我正在尝试将元组列表转换为以列表索引为键的字典 m = [(1, 'Sports', 222), (2, 'Tools', 11), (3, 'Clothing', 23)] 到目前为止,我已尝试使用: dict((i:{a,b,c}) for a,b,c in enumerate(m)) 但这是行不通的 我的预期产出是: {0: [1, 'Sports', 222], 1: [2, 'Tools', 11], 2: [3, 'Clothing', 23]} 使用
m = [(1, 'Sports', 222),
(2, 'Tools', 11),
(3, 'Clothing', 23)]
到目前为止,我已尝试使用:
dict((i:{a,b,c}) for a,b,c in enumerate(m))
但这是行不通的
我的预期产出是:
{0: [1, 'Sports', 222],
1: [2, 'Tools', 11],
2: [3, 'Clothing', 23]}
使用以下词典:
>>> {i:list(t) for i, t in enumerate(m)}
{0: [1, 'Sports', 222], 1: [2, 'Tools', 11], 2: [3, 'Clothing', 23]}
会有用的
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)
。。。对于enumerate(m)
中的i,(a、b、c)可以工作,但不需要解包元组而只重新打包这三个项。请注意,进行这种转换没有多大意义,因为原始列表提供了几乎相同的功能(项的键是它们的索引)