0
0
PythonHow-ToBeginner · 3 min read

How to Invert a Dictionary in Python: Simple Guide

To invert a dictionary in Python, swap its keys and values using a dictionary comprehension like {v: k for k, v in original_dict.items()}. This creates a new dictionary where original values become keys and original keys become values.
📐

Syntax

The basic syntax to invert a dictionary uses a dictionary comprehension:

  • {v: k for k, v in original_dict.items()}

Here, original_dict.items() gives pairs of keys and values. The comprehension swaps them to create a new dictionary with values as keys and keys as values.

python
{v: k for k, v in original_dict.items()}
💻

Example

This example shows how to invert a dictionary where keys are strings and values are numbers. It creates a new dictionary with numbers as keys and strings as values.

python
original_dict = {'apple': 1, 'banana': 2, 'cherry': 3}
inverted_dict = {v: k for k, v in original_dict.items()}
print(inverted_dict)
Output
{1: 'apple', 2: 'banana', 3: 'cherry'}
⚠️

Common Pitfalls

When inverting a dictionary, watch out for duplicate values in the original dictionary. Since dictionary keys must be unique, duplicates will be lost in the inverted dictionary.

For example, if two keys share the same value, only one will appear in the inverted dictionary.

python
original_dict = {'a': 1, 'b': 2, 'c': 1}
inverted_dict = {v: k for k, v in original_dict.items()}
print(inverted_dict)  # Output: {1: 'c', 2: 'b'}

# To handle duplicates, you can group keys into lists:
from collections import defaultdict
inverted_dict = defaultdict(list)
for k, v in original_dict.items():
    inverted_dict[v].append(k)
print(dict(inverted_dict))  # Output: {1: ['a', 'c'], 2: ['b']}
Output
{1: 'c', 2: 'b'} {1: ['a', 'c'], 2: ['b']}
📊

Quick Reference

Remember these tips when inverting dictionaries:

  • Use {v: k for k, v in dict.items()} for simple inversion.
  • Duplicate values in the original dictionary cause data loss in the inverted dictionary.
  • Use defaultdict(list) to group keys when duplicates exist.

Key Takeaways

Invert a dictionary by swapping keys and values with a dictionary comprehension.
Duplicate values in the original dictionary will overwrite keys in the inverted dictionary.
Use collections.defaultdict(list) to keep all keys for duplicate values when inverting.
Always check if values are unique before inverting to avoid data loss.