Python 中将元组列表转换成字典


在本文中,我们将学习如何将元组列表转换为字典。将元组列表转换为字典是一件很直观的事情。

按照以下步骤完成代码。

  • 使用元组对列表进行初始化。
  • 使用 dict 将给定的元组列表转换为字典。
  • 打印结果字典。

示例

我们来看看代码。

# initializing the list
tuples = [('Key 1', 1), ('Key 2', 2), ('Key 3', 3), ('Key 4', 4), ('Key 5', 5)]

# converting to dict
result = dict(tuples)

# printing the result
print(result)

如果你运行上面代码,你将得到以下结果。

输出

{'Key 1': 1, 'Key 2': 2, 'Key 3': 3, 'Key 4': 4, 'Key 5': 5}

让我们使用 setdefault() 方法在结果字典中添加值作为列表。

按照以下步骤完成代码。

  • 使用元组对列表进行初始化。
  • 遍历元组列表。
  • 设置键的默认值并添加值。
  • 打印结果。

示例

我们来看看代码。

# initializing the list
tuples = [('Key 1', 1), ('Key 2', 2), ('Key 3', 3), ('Key 4', 4), ('Key 5', 5)]

# result
result = {}

# iterating over the tuples lists
for (key, value) in tuples:
   # setting the default value as list([])
   # appending the current value
   result.setdefault(key, []).append(value)

# printing the list
print(result)

如果你运行上面代码,你将得到以下结果。

输出

{'Key 1': [1], 'Key 2': [2], 'Key 3': [3], 'Key 4': [4], 'Key 5': [5]}

总结

如果你对文章有任何疑问,可以在评论部分提出。

更新时间:2020 年 11 月 13 日

11K+ 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始吧
广告
© . All rights reserved.