Python Program to Convert Tuple to Dictionary

Write a Python program to Convert Tuple items to the dictionary. In Python, we can use the dict function to convert the tuple to dictionary. By default, it will assign the first item as the key and the second one as the dictionary value.

# Convert Tuple to Dictionary

tup = ((1, 'x'), (2, 'y'), (3, 'z'))
print(tup)
print("Data Type = ", type(tup))

tupToDict = dict(tup)
print(tupToDict)
print("Data Type = ", type(tupToDict))
Python Program to Convert Tuple to Dictionary 1

Python Program to Convert Tuple to Dictionary using for loop.

By using the for loop, we can change the dictionary key and values as per our requirement. For instance, we replaced the keys as values in the second example.

# Convert Tuple to Dictionary

tup = ((1, 'x'), (2, 'y'), (3, 'z'))
print(tup)

tupToDict1 = dict((key, value) for key, value in tup)
print(tupToDict1)
print("Data Type = ", type(tupToDict1))

tupToDict2 = dict((key, value) for value, key in tup)
print(tupToDict2)
print("Data Type = ", type(tupToDict2))

tupToDict3 = dict()
for key, value in tup:
    tupToDict3[key] =  value

print(tupToDict3)
print("Data Type = ", type(tupToDict3))
((1, 'x'), (2, 'y'), (3, 'z'))
{1: 'x', 2: 'y', 3: 'z'}
Data Type =  <class 'dict'>
{'x': 1, 'y': 2, 'z': 3}
Data Type =  <class 'dict'>
{1: 'x', 2: 'y', 3: 'z'}
Data Type =  <class 'dict'>

In this Python example, we used the dict, map functions to convert the tuple to the dictionary. Here, the reversed function will reverse or change the keys to values and vice versa. The second example uses the slice option to copy or convert all the tuple items to dictionary. In the third Convert Tuple to Dictionary example, we used a negative number as a slice (dict(i[::-1] for i in tup)) to change the dictionary key and values.

# Convert Tuple to Dictionary

tup = ((1, 'USA'), (2, 'UK'), (3, 'France'), (4, 'Germany'))
print(tup)

tupToDict1 = dict(map(reversed, tup))
print(tupToDict1)
print()

tupToDict2 = dict(i[::1] for i in tup)
print(tupToDict2)
print()

tupToDict3 = dict(i[::-1] for i in tup)
print(tupToDict3)
((1, 'USA'), (2, 'UK'), (3, 'France'), (4, 'Germany'))
{'USA': 1, 'UK': 2, 'France': 3, 'Germany': 4}

{1: 'USA', 2: 'UK', 3: 'France', 4: 'Germany'}

{'USA': 1, 'UK': 2, 'France': 3, 'Germany': 4}