Swap the keys and values of a dict to produce an inverse mapping. The replay shows inv growing one swapped entry at a time as the loop walks the original dict's items.

By hand

The Pythonic way

A dict comprehension over .items() expresses the swap in one line: swap the roles of k and v in the key-value assignment.

naive.py
m = {'r': 'red', 'g': 'green', 'b': 'blue', 'y': 'yellow', 'w': 'white'}
inv = {}
for k, v in m.items():
    inv[v] = k
print('RESULT:', {k: inv[k] for k in sorted(inv)})
library.py
m = {'r': 'red', 'g': 'green', 'b': 'blue', 'y': 'yellow', 'w': 'white'}
inv = {v: k for k, v in m.items()}
print('RESULT:', {k: inv[k] for k in sorted(inv)})
RESULT: {'blue': 'b', 'green': 'g', 'red': 'r', 'white': 'w', 'yellow': 'y'}

Implementation notes

  • Inversion is only well-defined when values are unique. If two keys share the same value, the loop silently overwrites the earlier entry and only the last key survives in inv — no error is raised.
  • The RESULT dict is built via {k: inv[k] for k in sorted(inv)} so the printed order is alphabetical by the original values (now keys), regardless of iteration order.
  • m.items() returns a view, not a copy; it is safe to iterate and read from simultaneously because the loop body only writes to inv, not m.