w3resource

Python Exercise: Convert a tuple to a dictionary

Python tuple: Exercise-16 with Solution

Write a Python program to convert a tuple to a dictionary.

Visual Presentation:

Python Tuple: Convert a tuple to a dictionary.

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:

Flowchart: Convert a tuple to a dictionary

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/tuple/python-tuple-exercise-16.php