How to Swap Keys and Values in Dictionary in Python
To swap keys and values in a Python dictionary, use 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 syntax to swap keys and values in 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 creates a new dictionary with v as the new key and k as the new value.
python
{v: k for k, v in original_dict.items()}Example
This example shows how to swap keys and values in a dictionary of fruits and their colors.
python
original_dict = {'apple': 'red', 'banana': 'yellow', 'grape': 'purple'}
swapped_dict = {v: k for k, v in original_dict.items()}
print(swapped_dict)Output
{'red': 'apple', 'yellow': 'banana', 'purple': 'grape'}
Common Pitfalls
One common mistake is when dictionary values are not unique. Since keys must be unique, swapping will lose data if values repeat.
For example, if two keys have the same value, only one will appear in the swapped dictionary.
python
original_dict = {'a': 1, 'b': 1}
swapped_dict = {v: k for k, v in original_dict.items()}
print(swapped_dict) # Output: {1: 'b'}
# Correct approach if values repeat is to store keys in a list:
from collections import defaultdict
swapped_dict = defaultdict(list)
for k, v in original_dict.items():
swapped_dict[v].append(k)
print(dict(swapped_dict)) # Output: {1: ['a', 'b']}Output
{1: 'b'}
{1: ['a', 'b']}
Quick Reference
Tips for swapping keys and values in Python dictionaries:
- Use dictionary comprehension:
{v: k for k, v in dict.items()} - Ensure values are unique to avoid data loss
- Use
defaultdict(list)to handle duplicate values
Key Takeaways
Use dictionary comprehension to swap keys and values easily.
Original dictionary values must be unique to avoid losing data.
For duplicate values, group keys in a list using defaultdict.
Swapping creates a new dictionary; original stays unchanged.
Always check data types to ensure keys are hashable after swap.