Python Exercise: 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:
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics