数据类型之间的转换是非常流行的实用程序,因此了解它总是被证明非常方便。前面已经讨论过将元组列表转换为字典,有时,我们可能有一个键和一个值元组要转换为字典。让我们讨论一些可以执行此操作的方法。
方法#1:使用字典理解
可以使用字典推导来执行此任务,在其中我们可以使用同时迭代键和值元组enumerate()
并构造所需的字典。
# Python3 code to demonstrate working of
# Convert Tuples to Dictionary
# Using Dictionary Comprehension
# Note:For conversion of two tuples into a dictionary, we've to have the same length of tuples. Otherwise, we can not match all the key-value pairs
# initializing tuples
test_tup1 = ('GFG', 'is', 'best')
test_tup2 = (1, 2, 3)
# printing original tuples
print("The original key tuple is:" + str(test_tup1))
print("The original value tuple is:" + str(test_tup2))
# Using Dictionary Comprehension
# Convert Tuples to Dictionary
if len(test_tup1) == len(test_tup2):
res = {test_tup1[i]:test_tup2[i] for i, _ in enumerate(test_tup2)}
# printing result
print("Dictionary constructed from tuples:" + str(res))
输出:
The original key tuple is:('GFG', 'is', 'best') The original value tuple is:(1, 2, 3) Dictionary constructed from tuples:{'best':3, 'is':2, 'GFG':1}
方法#2:使用zip() + dict()
这是可以执行此任务的另一种方法,其中结合了zip
function 和 dict 函数实现了这个任务。这zip
函数负责将元组转换为具有相应索引的键值对。这dict
函数执行转换为字典的任务。
# Python3 code to demonstrate working of
# Convert Tuples to Dictionary
# Using zip() + dict()
# initializing tuples
test_tup1 = ('GFG', 'is', 'best')
test_tup2 = (1, 2, 3)
# printing original tuples
print("The original key tuple is:" + str(test_tup1))
print("The original value tuple is:" + str(test_tup2))
# Using zip() + dict()
# Convert Tuples to Dictionary
if len(test_tup1) == len(test_tup2):
res = dict(zip(test_tup1, test_tup2))
# printing result
print("Dictionary constructed from tuples:" + str(res))
输出:
The original key tuple is:('GFG', 'is', 'best') The original value tuple is:(1, 2, 3) Dictionary constructed from tuples:{'GFG':1, 'is':2, 'best':3}
注:本文由纯净天空筛选整理自manjeet_04大神的英文原创作品 Python | Convert Tuples to Dictionary。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。