當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python Tuples轉Dictionary用法及代碼示例


數據類型之間的轉換是非常流行的實用程序,因此了解它總是被證明非常方便。前麵已經討論過將元組列表轉換為字典,有時,我們可能有一個鍵和一個值元組要轉換為字典。讓我們討論一些可以執行此操作的方法。

方法#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()
這是可以執行此任務的另一種方法,其中結合了zipfunction 和 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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。