Conversions among datatypes are quite popular utilities and hence having knowledge of it always proves out to be quite handy. The conversion of a list of tuples into a dictionary had been discussed earlier, sometimes, we might have a key and a value tuple to be converted to a dictionary. Let’s discuss certain ways in which this can be performed.
Method #1: Using Dictionary Comprehension
This task can be performed using dictionary comprehension in which we can iterate through the key and value tuple simultaneously using enumerate() and construct the desired dictionary.
Here’s a step-by-step approach :
- Initialize two tuples test_tup1 and test_tup2.
- Print the original tuples using the print() function and str() function to convert them into strings.
- Check if the length of both tuples is equal using the len() function.
- If the length of both tuples is equal, use dictionary comprehension to create a dictionary. Here, test_tup1[i] is the key and test_tup2[i] is the value for the ith element of both tuples. The enumerate() function is used to get the index and value of each element of test_tup2.
- Print the resulting dictionary using the print() function and str() function to convert it into a string.
Python3
# Python code to convert into dictionary def Convert(tup, di): for a, b in tup: di.setdefault(a, []).append(b) return di # Driver Code tups = [( "akash" , 10 ), ( "gaurav" , 12 ), ( "anand" , 14 ), ( "suraj" , 20 ), ( "akhil" , 25 ), ( "ashish" , 30 )] dictionary = {} print (Convert(tups, dictionary)) |
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}
Time complexity: O(n), where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(n), to store the keys and values in dictionary.
Method #2: Using zip() + dict()
This is yet another method in which this task can be performed in which a 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.
Python3
# 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}
Time complexity: O(n), where n is the length of the tuples.
Auxiliary space: O(n), where n is the length of the tuples.
Method 3: Using a loop
This method creates an empty dictionary and iterates over the indices of the first tuple. It then uses these indices to access the corresponding elements in both tuples and populates the dictionary. Finally, it prints the resulting dictionary.
Python3
# initializing tuples test_tup1 = ( 'GFG' , 'is' , 'best' ) test_tup2 = ( 1 , 2 , 3 ) # initialize empty dictionary res = {} # Using loop to populate the dictionary for i in range ( len (test_tup1)): res[test_tup1[i]] = test_tup2[i] # printing result print ( "Dictionary constructed from tuples : " + str (res)) |
Dictionary constructed from tuples : {'GFG': 1, 'is': 2, 'best': 3}
Time complexity: O(n), where n is the length of the tuples.
Auxiliary space: O(n), where n is the length of the tuples.
Method #4: Using the map() function
The program converts two tuples into a dictionary using the map() function and prints the resulting dictionary. The map() function applies the lambda function to pair up corresponding elements from the two tuples and return the resulting key-value pairs, which are then used to construct the dictionary.
Python3
# Python3 code to demonstrate working of # Convert Tuples to Dictionary # Using map() function # 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 map() function # Convert Tuples to Dictionary if len (test_tup1) = = len (test_tup2): res = dict ( map ( lambda x, y: (x, y), 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}
Time complexity: O(n), where n is the length of the tuples.
Auxiliary space: O(n), as it requires space to store the resulting dictionary.
Method #5: Using the setdefault() method
- It uses setdefault method of dictionaries to convert the tuples to a dictionary.
- The setdefault method returns the value of a key in the dictionary, and if the key is not present, it sets the key to the empty list.
- Printing the result
Python3
# Python3 code to demonstrate working of # Convert Tuples to Dictionary # Using setdefault() function # 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)) # Python code to convert tuple into dictionary def convertTup(test_tup1, test_tup2): for a, b in test_tup1: test_tup2.setdefault(a, []).append(b) return test_tup2 # calling function to convert tuples to dictionary res = {} convertTup( zip (test_tup1, test_tup2), res) # 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]}
Time complexity: O(n), where n is the length of the tuples.
Auxiliary space: O(n), as it requires space to store the resulting dictionary.
Method #6: Using itertools.zip_longest()
Step-by-Step Algorithm:
- Import the itertools module.
- Initialize the key_tuple and value_tuple with the given tuples.
- Use itertools.zip_longest() to combine the two tuples into a list of tuples, with fillvalue set to None.
- Use dict() to convert the list of tuples to a dictionary.
- Store the resulting dictionary in the result_dict variable.
- Print the dictionary.
Python3
import itertools key_tuple = ( 'GFG' , 'is' , 'best' ) value_tuple = ( 1 , 2 , 3 ) # printing original tuples print ( "The original key tuple is : " + str (key_tuple)) print ( "The original value tuple is : " + str (value_tuple)) result_list = itertools.zip_longest(key_tuple, value_tuple, fillvalue = None ) result_dict = dict (result_list) print ( "Dictionary constructed from tuples :" , result_dict) |
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}
Time complexity: O(n), where n is the length of the tuples.
Auxiliary space: O(n), as it requires space to store the resulting dictionary.