How to swap dict keys and values in Python when values are unique

Swap dict keys and values using a dict comprehension, with a guard that raises an error when values repeat.

Easy Python 3.9+ Aug 9, 2026 Dictionaries & sets 14 views 0 copies

Python code

11 lines
Python 3.9+
def swap_dict_keys_values(d):
    """Swap keys and values in a dict, assuming values are unique."""
    if len(set(d.values())) != len(d.values()):
        raise ValueError("Values must be unique to swap keys and values")
    return {v: k for k, v in d.items()}

if __name__ == "__main__":
    original = {"a": 1, "b": 2, "c": 3}
    result = swap_dict_keys_values(original)
    print(f"Original: {original}")
    print(f"Swapped: {result}")

Output

stdout
Original: {'a': 1, 'b': 2, 'c': 3}
Swapped: {1: 'a', 2: 'b', 3: 'c'}

How it works

This works because a dictionary comprehension builds a new mapping by iterating over the original items with {v: k for k, v in d.items()}. The guard len(set(d.values())) != len(d.values()) detects duplicate values first, since losing keys in a swap would silently corrupt the data. Swapping is inherently reversible only when each value maps to exactly one key, making the uniqueness check essential. When values are unique, the result is a valid dict where the old values become keys and old keys become values. This pattern is O(n) and requires no third-party libraries.

Common mistakes

  • Swapping without checking uniqueness can silently drop keys when values collide
  • Using `dict(zip(d.values(), d.keys()))` which does the same but is less readable
  • Assuming values are hashable — non-hashable values (like lists) will raise TypeError

Variations

  1. Use `{value: key for key, value in d.items()}` inline without a function if you already know values are unique
  2. Use `dict(map(reversed, d.items()))` as a compact one-liner for small dicts

Real-world use cases

  • Inverting an ID-to-name lookup table so you can search by name instead of ID.
  • Mapping external codes to internal identifiers when integrating two APIs.
  • Building a reverse index from product names to SKU numbers for faster lookups.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Dictionaries & sets

Related tutorials and quizzes for this topic.