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]}结论
如果您对本文有任何疑问,请在评论部分中提及它们。