How to Invert a Dictionary in Python Safely

Swap dictionary keys and values while detecting duplicate values to prevent silent data loss.

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

Python code

19 lines
Python 3.9+
def 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

stdout
{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

  1. Use collections.defaultdict to collect all original keys per value if you want to keep duplicates
  2. 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

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.