📜  Python|将元组转换为字典

📅  最后修改于: 2022-05-13 01:55:51.264000             🧑  作者: Mango

Python|将元组转换为字典

数据类型之间的转换是非常流行的实用程序,因此了解它总是被证明非常方便。前面已经讨论过将元组列表转换为字典,有时,我们可能有一个键和一个值元组要转换为字典。让我们讨论可以执行此操作的某些方式。

方法#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函数和 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}