Python | Convert Tuples to Dictionary

Conversions among datatypes is quite popular utility and hence having knowledge of it always proves out to be quite handy. The conversion of list of tuples into dictionary had been discussed earlier, sometimes, we might have a key and a value tuple to be converted to dictionary. Let’s discuss certain ways in which this can be performed.

Method #1 : Using Dictionary Comprehension
This task can be performed using the dictionary comprehension in which we can iterate through the key and value tuple simultaneously using enumerate() and construct the desired dictionary.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Convert Tuples to Dictionary
# Using Dictionary Comprehension
  
# 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
res = {test_tup1[i] : test_tup2[i] for i, _ in enumerate(test_tup2)}
  
# printing result 
print("Dictionary constructed from tuples : " + str(res))

chevron_right


Output :

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}

 

Method #2 : Using zip() + dict()
This is yet another method in which this task can be performed in which combination of zip function and dict function achieve this task. The zip function is responsible for conversion of tuple to key-value pair with corresponding indices. The dict function performs the task of conversion to dictionary.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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
res = dict(zip(test_tup1, test_tup2))
  
# printing result 
print("Dictionary constructed from tuples : " + str(res))

chevron_right


Output :

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}


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.