【问题标题】:How to convert list of tuples to dictionary with index as key如何将元组列表转换为以索引为键的字典
【发布时间】:2020-05-09 17:42:56
【问题描述】:

我正在尝试将元组列表转换为以列表索引为键的字典。

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

【问题讨论】:

  • ... for i, (a, b, c) in enumerate(m) 会起作用,但解包元组只是为了再次打包这三个项目是不必要的。
  • 请注意,进行这种转换并没有多大意义,因为您拥有的原始列表提供了几乎相同的功能(项目的键是它们的索引)

标签: python list dictionary tuples dictionary-comprehension


【解决方案1】:

会有用的

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)

【讨论】:

    【解决方案2】:

    使用以下字典理解:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-09
      • 2018-10-29
      • 1970-01-01
      • 2016-07-27
      • 2011-09-29
      • 1970-01-01
      • 1970-01-01
      • 2019-06-08
      相关资源
      最近更新 更多