Invert a Dictionary
Completed
Read n lines of key value. Build a dict, then invert it (values become keys). Print the inverted pairs sorted by the new key as key -> value.
Input
Line 1: n. Then n lines (values are unique).
Output
n lines.
Example
Input
3 red 1 green 2 blue 3
Output
1 -> red 2 -> green 3 -> blue
Editor
Python
Hints
dict() accepts a sequence of 2-item pairs.
A dict comprehension: {v: k for k, v in d.items()}.
Solution explanation
Dict comprehensions build dictionaries the same way list comprehensions build lists.
Show solution
n = int(input())
d = dict(input().split() for _ in range(n))
inverted = {v: k for k, v in d.items()}
for k in sorted(inverted):
print(f"{k} -> {inverted[k]}")