How I can convert a Python Tuple into Dictionary?

PythonServer Side ProgrammingProgramming

The tuple elements are enclosed inside the parenthesis, while dictionary elements are present in the form of a key-value pair and are enclosed between curly brackets.

In this article, we will show you how to convert a python tuple into a dictionary. The following are the methods to convert a tuple into a dictionary −

  • Using dict() function

  • Using Dictionary Comprehension and enumerate() function

  • Using zip() and dict() functions

Assume we have taken a tuple containing some elements. We will convert the input tuple into a python dictionary and return it using different methods as specified above.

Method 1: Using dict() function

In Python, use the dict() function to convert a tuple to a dictionary. A dictionary object can be created with the dict() function. The dictionary is returned by the dict() method, which takes a tuple of tuples as an argument. A key-value pair is contained in each tuple.

Here in the below code, To create a dictionary, we used the dict() method and gave the dictionary comprehension as an argument. Dictionary comprehension is a technique for converting one dictionary into another. Elements from the original dictionary can be conditionally included in the new dictionary throughout this conversion, and each element can be converted as needed.

The output is a key-value paired dictionary. The first element of a tuple becomes a dictionary key, while the second element of a tuple becomes a dictionary value.

Example

The following program converts a tuple into a dictionary using the dict() function −

# input tuple inputTuple = ((5, "TutorialsPoint"), (6, "Python"), (7, "Codes")) print("The input Tuple:", inputTuple) # Here we are iterating through each element (pairs) of the tuple using dictionary comprehension and converting it to the dictionary resultDictionary = dict((x, y) for x, y in inputTuple) print("The result dictionary:", resultDictionary)

Output

On executing, the above program will generate the following output −

The input Tuple: ((5, 'TutorialsPoint'), (6, 'Python'), (7, 'Codes'))
The result dictionary: {5: 'TutorialsPoint', 6: 'Python', 7: 'Codes'}

Method 2: Using Dictionary Comprehension and enumerate () function

NOTE − To convert two tuples into a dictionary, the tuples must be the same length. Otherwise, we won't be able to match all of the key-value pairs.

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task

  • Create two variables to store the first and second input tuples having the same length.

  • Use the if conditional statement, to check whether the length of both the tuples is the equal length or not.

  • Convert both the tuples into a dictionary using enumerate() function in a dictionary comprehension, if the condition is true.

  • Printing the result dictionary from the given two tuples after conversion.

The enumerate() method adds a counter to an iterable and returns the enumerate object.

Syntax

enumerate(iterable, start=0)

Parameters

iterable − It can be any sequence/object/iterable supporting iteration

start − enumerate() begins counting from this value. If start is not specified, the value 0 is used.

Example

The following program converts both tuples into a dictionary using the dictionary comprehension method(one tuple as keys and the other as values of dictionary) −

# input tuple_1 inputTuple_1 = ('TutorialsPoint', 'Python', 'Codes') # input tuple_2 inputTuple_2 = (5, 6, 7) # printing the input tuple_1(keys) print("The input Tuple_1(keys) = ", inputTuple_1) # printing the input tuple_2(values) print("The input Tuple_2(values) = ", inputTuple_2) # Checking whether the length of both the tuples are equal or not if len(inputTuple_1) == len(inputTuple_2): # converting both the tuples into a dictionary using enumerate() # function in a dictionary comprehension resultDictionary = {inputTuple_1[i] : inputTuple_2[i] for i, _ in enumerate(inputTuple_2)} # printing the result dictionary from the given two tuples print("The result dictionary:", resultDictionary)

Output

The input Tuple_1(keys) = ('TutorialsPoint', 'Python', 'Codes')
The input Tuple_2(values) = (5, 6, 7)
The result dictionary: {'TutorialsPoint': 5, 'Python': 6, 'Codes': 7} 

Method 3: Using zip() and dict() functions

Algorithm (Steps)

  • Create two variables to store the first and second input tuples having the same length.

  • Use the if conditional statement, to check whether the length of both the tuples is the equal length or not.

  • Convert both the tuples into a dictionary using zip() and dict() functions, if the condition is true.

    zip() method − The zip() method takes iterables (which might be zero or more), combines them into a tuple, and returns it.

Syntax- zip(*iterables)
  • dict() function − The dict() function is used to create a dictionary.

  • Printing the result dictionary from the given two tuples after conversion.

Example

The following program converts both tuples into a dictionary using the zip and dict() functions (one tuple as keys and the other as values of dictionary) −

# input tuple_1 inputTuple_1 = ('TutorialsPoint', 'Python', 'Codes') # input tuple_2 inputTuple_2 = (5, 6, 7) # printing the input tuple_1(keys) print("The input Tuple_1(keys) = ", inputTuple_1) # printing the input tuple_2(values) print("The input Tuple_2(values) = ", inputTuple_2) # Checking whether the length of both the tuples are equal or not if len(inputTuple_1) == len(inputTuple_2): # converting both the tuples into a dictionary using zip() # and dict() functions # Here zip function takes elements of input tuple 1 as keys and input tuple 2 elements as values # Then we convert this to a dictionary using dict() resultDictionary = dict(zip(inputTuple_1, inputTuple_2)) # printing result dictionary from the given two tuples print("The result dictionary:", resultDictionary)

Output

The input Tuple_1(keys) = ('TutorialsPoint', 'Python', 'Codes')
The input Tuple_2(values) = (5, 6, 7)
The result dictionary: {'TutorialsPoint': 5, 'Python': 6, 'Codes': 7}

Conclusion

We learned how to convert a tuple to a dictionary using three different functions in this article. We also observed that if there are two tuples, we can create a dictionary by using two different methods, zip() and enumerate(), to take the first tuple elements as keys and the second tuple elements as values ()

raja
Updated on 08-Nov-2022 11:56:19

Advertisements