0
0
Pythonprogramming~5 mins

Inverting a dictionary in Python

Choose your learning style9 modes available
Introduction

Inverting a dictionary means swapping its keys and values. This helps when you want to look up original keys by their values.

You have a dictionary of country codes to country names and want to find the code by name.
You store usernames as keys and user IDs as values, and want to find usernames by ID.
You have a mapping of product IDs to product names and want to find the ID by name.
Syntax
Python
inverted_dict = {value: key for key, value in original_dict.items()}

This creates a new dictionary where each original value becomes a key, and each original key becomes a value.

Make sure original values are unique and hashable, or you may lose data or get errors.

Examples
Simple example swapping letters and numbers.
Python
original = {'a': 1, 'b': 2}
inverted = {v: k for k, v in original.items()}
print(inverted)
Inverts a dictionary of foods to their types.
Python
original = {'apple': 'fruit', 'carrot': 'vegetable'}
inverted = {v: k for k, v in original.items()}
print(inverted)
If values repeat, the last key wins in the inverted dictionary.
Python
original = {'x': 10, 'y': 10}
inverted = {v: k for k, v in original.items()}
print(inverted)
Sample Program

This program inverts a color-to-hex dictionary so you can find the color name by its hex code.

Python
original_dict = {'red': '#FF0000', 'green': '#00FF00', 'blue': '#0000FF'}
inverted_dict = {value: key for key, value in original_dict.items()}
print('Original:', original_dict)
print('Inverted:', inverted_dict)
OutputSuccess
Important Notes

If original values are not unique, some keys will be lost in the inverted dictionary.

Values must be hashable (like strings, numbers, or tuples) to be dictionary keys.

Summary

Inverting swaps keys and values in a dictionary.

Use dictionary comprehension with .items() to invert.

Be careful with duplicate values and unhashable types.