0
0
PythonProgramBeginner · 2 min read

Python Program to Invert a Dictionary

You can invert a dictionary in Python by using a dictionary comprehension like {v: k for k, v in original_dict.items()} which swaps keys and values.
📋

Examples

Input{"a": 1, "b": 2}
Output{"1": "a", "2": "b"}
Input{"x": 10, "y": 20, "z": 30}
Output{"10": "x", "20": "y", "30": "z"}
Input{}
Output{}
🧠

How to Think About It

To invert a dictionary, think of swapping each key with its value. Since dictionaries have unique keys, the values must be unique to become keys in the new dictionary. You go through each pair, take the value as the new key, and the key as the new value.
📐

Algorithm

1
Get the original dictionary.
2
Create a new empty dictionary for the inverted result.
3
For each key-value pair in the original dictionary, add a new pair to the new dictionary with the value as key and the key as value.
4
Return the new inverted dictionary.
💻

Code

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

Dry Run

Let's trace the dictionary {'a': 1, 'b': 2, 'c': 3} through the code

1

Start with original dictionary

{'a': 1, 'b': 2, 'c': 3}

2

Iterate over items

('a', 1), ('b', 2), ('c', 3)

3

Swap key and value for each pair

Add 1: 'a', 2: 'b', 3: 'c' to new dictionary

4

Resulting inverted dictionary

{1: 'a', 2: 'b', 3: 'c'}

Original KeyOriginal ValueNew KeyNew Value
a11a
b22b
c33c
💡

Why This Works

Step 1: Access original pairs

The code uses .items() to get each key and value from the original dictionary.

Step 2: Swap keys and values

Inside the dictionary comprehension, v: k flips the original key-value pair.

Step 3: Create new dictionary

The comprehension builds a new dictionary with swapped pairs without changing the original.

🔄

Alternative Approaches

Using a for loop
python
original_dict = {'a': 1, 'b': 2}
inverted_dict = {}
for k, v in original_dict.items():
    inverted_dict[v] = k
print(inverted_dict)
This is more verbose but easier to understand for beginners.
Using dict constructor with map
python
original_dict = {'a': 1, 'b': 2}
inverted_dict = dict(map(lambda item: (item[1], item[0]), original_dict.items()))
print(inverted_dict)
Uses functional programming style but less readable for beginners.

Complexity: O(n) time, O(n) space

Time Complexity

The code loops through all items once, so time grows linearly with the number of items.

Space Complexity

A new dictionary is created with the same number of items, so space also grows linearly.

Which Approach is Fastest?

Dictionary comprehension and for loop have similar speed; dict with map is slightly slower due to function calls.

ApproachTimeSpaceBest For
Dictionary comprehensionO(n)O(n)Concise and fast for unique values
For loopO(n)O(n)Clear and beginner-friendly
dict with mapO(n)O(n)Functional style, less readable
💡
Make sure the original dictionary's values are unique and hashable to avoid losing data when inverting.
⚠️
Trying to invert a dictionary with duplicate values causes data loss because keys must be unique.