Reference library

Dictionaries & sets

Key–value maps, uniqueness, counting, grouping, and fast lookups.

2 matches
Dictionaries & sets easy

How to Invert a Dictionary in Python Safely

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

dictionary inversion data-safety
Python
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,…
15 0 Open
Dictionaries & sets easy

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.

dictionary comprehension keys-values
Python
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": …
14 0 Open

Browse by section

Each section groups closely related Python snippets.

Dictionaries & sets — Python code examples

What you will find here

This page collects dictionaries & sets snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.