Python Practice › Tuple Programs › Program 23

Tuple of pairs to a dictionary

EasyTuple Programs · 23 of 70

Write a Python program to convert a tuple of (value, key) pairs into a dictionary keyed by the second item.

Advertisement
Input
((5, "s"), (6, "l"))
Output
{'s': 5, 'l': 6}

Approach

  1. A dict comprehension swaps the order.

Solution

Python
pairs = ((5, "s"), (6, "l"))print({key: value for value, key in pairs})
Output
{'s': 5, 'l': 6}
Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More tuple programs

← All 70 Tuple Programs