Python Exercise: Convert a tuple to a dictionary
16. Convert a Tuple to a Dictionary
Write a Python program to convert a tuple to a dictionary.
Visual Presentation:

Sample Solution:
Python Code:
# Create a tuple containing nested tuples, where each inner tuple consists of two elements.
tuplex = ((2, "w"), (3, "r"))
# Create a dictionary by using a generator expression to swap the elements of each inner tuple.
# The generator iterates through 'tuplex', and for each inner tuple (x, y), it creates a key-value pair (y, x).
result_dict = dict((y, x) for x, y in tuplex)
# Print the resulting dictionary.
print(result_dict)
Sample Output:
{'w': 2, 'r': 3}
Flowchart:

For more Practice: Solve these Related Problems:
- Write a Python program to convert a tuple of two-element tuples into a dictionary using dict().
- Write a Python program to iterate over a tuple and create a dictionary where each pair of consecutive elements forms a key-value pair.
- Write a Python program to use dictionary comprehension to transform a tuple of pairs into a dictionary.
- Write a Python program to convert a tuple with an even number of elements into a dictionary by pairing adjacent items.
Python Code Editor:
Previous: Write a Python program to find the length of a tuple.
Next: Write a Python program to unzip a list of tuples into individual lists.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.