How to Invert a Dictionary in Python Safely
Swap dictionary keys and values while detecting duplicate values to prevent silent data loss.
Python code
19 linesdef invert_dict_safely(d):
inverted = {}
for key, value in d.items():
if value not in inverted:
inverted[value] = key
else:
raise ValueError(f"Duplicate value '{value}' would cause data loss")
return inverted
if __name__ == "__main__":
sample = {"a": 1, "b": 2, "c": 3}
print(invert_dict_safely(sample))
try:
problematic = {"x": 10, "y": 10}
invert_dict_safely(problematic)
except ValueError as e:
print(f"Error: {e}")
Output
{1: 'a', 2: 'b', 3: 'c'}
Error: Duplicate value '10' would cause data loss
How it works
The code iterates through d.items() to access each key-value pair. For each value, it checks if the value already exists as a key in the inverted dictionary. If not, it assigns the original key as the new value. If a duplicate is found, it raises a ValueError to alert the programmer about potential data loss, since only one key can survive the inversion. This approach guarantees reversibility and makes the function predictable in production code.
Common mistakes
- Using a naive dict comprehension like {v: k for k, v in d.items()} which silently overwrites earlier keys on duplicates
- Forgetting that values must be hashable to be used as dictionary keys
- Not handling duplicate values when building the inverted map, leading to lost data
- Assuming the original dictionary is always unique on values without checking
Variations
- Use collections.defaultdict to collect all original keys per value if you want to keep duplicates
- Use a try-except around assignment instead of a membership check for slightly faster code
Real-world use cases
- Mapping user IDs to usernames when you need to look up users by their unique ID.
- Converting API response field mappings where you need reverse lookups for validation.
- Building reverse indexes for search, e.g., flipping word-to-document maps to document-to-words.
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.