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.
Python code
11 linesdef 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
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
- Use `{value: key for key, value in d.items()}` inline without a function if you already know values are unique
- 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
More from Dictionaries & sets
- Build a Case-Insensitive Dict with a Wrapper Class in Python medium
- Build a defaultdict histogram of categories in Python easy
- Build adjacency dict graph from edges in Python easy
- Build an OrderedDict insertion order demo in Python 3 easy
- Check Invertible Mapping for Duplicate Values in Python easy
- Compare Two Dictionaries in Python easy
Keep learning
Related tutorials and quizzes for this topic.