Python Practice › Tuple Programs › Program 23
Tuple of pairs to a dictionary
Write a Python program to convert a tuple of (value, key) pairs into a dictionary keyed by the second item.
Input
((5, "s"), (6, "l"))
Output
{'s': 5, 'l': 6}Approach
- A dict comprehension swaps the order.
Solution
pairs = ((5, "s"), (6, "l"))print({key: value for value, key in pairs})Output
{'s': 5, 'l': 6}Learn the concept
New to this topic? Read the lesson, then come back.