Check Invertible Mapping for Duplicate Values in Python

Detect duplicate values among (key, value) pairs to ensure the mapping is invertible, using a dictionary for O(1) lookups.

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

Python code

20 lines
Python 3.9+
def invertible_after_dedup(pairs):
    """
    Check whether a set of (key, value) pairs is invertible,
    i.e., no duplicate values exist for different keys.
    """
    seen = {}
    for key, value in pairs:
        if value in seen and seen[value] != key:
            return False, f"Duplicate value '{value}' for keys '{seen[value]}' and '{key}'"
        seen[value] = key
    return True, "All values are unique"

if __name__ == "__main__":
    data = [("a", 1), ("b", 2), ("c", 1)]
    ok, msg = invertible_after_dedup(data)
    print(f"Invertible: {ok} — {msg}")

    data2 = [("x", 10), ("y", 20), ("z", 30)]
    ok2, msg2 = invertible_after_dedup(data2)
    print(f"Invertible: {ok2} — {msg2}")

Output

stdout
Invertible: False — Duplicate value '1' for keys 'a' and 'c'
Invertible: True — All values are unique

How it works

The function iterates through each (key, value) pair and stores the value as a key in a dictionary, mapping to the original key. On subsequent pairs, if the same value appears and the stored key differs, it immediately returns False, indicating non-invertibility. If no duplicates are found, it returns True. This algorithm runs in O(n) time and O(n) space, making it efficient for large datasets. The function also provides a descriptive message for debugging, helping identify which duplicated value and keys caused the failure.

Common mistakes

  • Forgetting to check if the existing key is different, which would incorrectly flag identical keys as duplicates.
  • Overwriting seen[value] without first verifying, causing missed duplicate detections.
  • Assuming duplicate values are always an error without considering same-key repeats.

Variations

  1. Use a set to track seen values, but lose the ability to report which keys conflict.
  2. Return only a boolean if you don't need diagnostic messages.

Real-world use cases

  • Validating that a user-to-email mapping has unique emails before saving to a database.
  • Checking that a config file maps each port to exactly one service to avoid conflicts.
  • Verifying that API response IDs are unique when building an index from fetched data.

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.