Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to Swap Keys and Values in Dictionary
Dictionaries are a fundamental data structure in Python, providing a way to store key-value pairs. Sometimes you need to reverse the roles of keys and values in a dictionary. This operation is useful for data restructuring, creating value-based lookups, or removing duplicates.
In this article, we will explore different methods to swap keys and values in a Python dictionary with practical examples.
Understanding the Problem
Swapping keys and values in a dictionary means creating a new dictionary where the original values become keys and the original keys become values. This is useful in scenarios such as:
Data Restructuring ? When keys represent categories and values represent data points
Unique Value Mapping ? Creating value-based lookups when original values are unique
Removing Duplicates ? Identifying duplicate values by making them keys
Using Dictionary Comprehension
The most Pythonic way to swap keys and values is using dictionary comprehension ?
def swap_keys_values(dictionary):
return {value: key for key, value in dictionary.items()}
# Example 1: Simple key-value swap
my_dict = {'a': 1, 'b': 2, 'c': 3}
swapped_dict = swap_keys_values(my_dict)
print("Original:", my_dict)
print("Swapped:", swapped_dict)
Original: {'a': 1, 'b': 2, 'c': 3}
Swapped: {1: 'a', 2: 'b', 3: 'c'}
Handling Duplicate Values
When the original dictionary contains duplicate values, swapping will result in lost data since dictionary keys must be unique ?
# Dictionary with duplicate values
my_dict = {'apple': 'fruit', 'carrot': 'vegetable', 'banana': 'fruit'}
swapped_dict = swap_keys_values(my_dict)
print("Original:", my_dict)
print("Swapped:", swapped_dict)
print("Note: 'apple' was overwritten by 'banana'")
Original: {'apple': 'fruit', 'carrot': 'vegetable', 'banana': 'fruit'}
Swapped: {'fruit': 'banana', 'vegetable': 'carrot'}
Note: 'apple' was overwritten by 'banana'
Using dict() Constructor
An alternative approach using the dict() constructor with a generator expression ?
def swap_using_dict_constructor(dictionary):
return dict((value, key) for key, value in dictionary.items())
# Example with string keys and integer values
my_dict = {1: 'one', 2: 'two', 3: 'three'}
swapped_dict = swap_using_dict_constructor(my_dict)
print("Original:", my_dict)
print("Swapped:", swapped_dict)
Original: {1: 'one', 2: 'two', 3: 'three'}
Swapped: {'one': 1, 'two': 2, 'three': 3}
Preserving Duplicate Values with Lists
To handle duplicate values without losing data, store multiple keys in lists ?
def swap_preserve_duplicates(dictionary):
swapped_dict = {}
for key, value in dictionary.items():
if value in swapped_dict:
swapped_dict[value].append(key)
else:
swapped_dict[value] = [key]
return swapped_dict
# Example with duplicate values
my_dict = {'apple': 'fruit', 'carrot': 'vegetable', 'banana': 'fruit', 'orange': 'fruit'}
swapped_dict = swap_preserve_duplicates(my_dict)
print("Original:", my_dict)
print("Swapped with preserved duplicates:", swapped_dict)
Original: {'apple': 'fruit', 'carrot': 'vegetable', 'banana': 'fruit', 'orange': 'fruit'}
Swapped with preserved duplicates: {'fruit': ['apple', 'banana', 'orange'], 'vegetable': ['carrot']}
Comparison of Methods
| Method | Handles Duplicates? | Best For |
|---|---|---|
| Dictionary Comprehension | No (overwrites) | Simple swapping with unique values |
| dict() Constructor | No (overwrites) | Alternative syntax preference |
| List Preservation | Yes (stores in lists) | Preserving all original keys |
Conclusion
Dictionary comprehension is the most efficient method for swapping keys and values when values are unique. For duplicate values, use the list preservation method to avoid data loss. Choose the approach based on your specific requirements and data characteristics.
