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 dictionary item_s position
Dictionaries in Python are versatile data structures that store key-value pairs. Sometimes we need to swap the values of two keys within a dictionary. This article demonstrates different approaches to swap dictionary item values efficiently.
Understanding Dictionary Value Swapping
When we swap dictionary items, we exchange the values associated with two specific keys. For example, given {'A': 1, 'B': 2, 'C': 3}, swapping values of keys 'A' and 'B' results in {'A': 2, 'B': 1, 'C': 3}.
Method 1: Using Tuple Unpacking
The most Pythonic way uses simultaneous assignment with tuple unpacking ?
def swap_dict_values(dictionary, key1, key2):
"""Swap values of two keys in a dictionary"""
if key1 in dictionary and key2 in dictionary:
dictionary[key1], dictionary[key2] = dictionary[key2], dictionary[key1]
else:
print("One or both keys not found in dictionary")
return dictionary
# Example usage
my_dict = {'A': 1, 'B': 2, 'C': 3, 'D': 4}
print("Original dictionary:", my_dict)
# Swap values of 'A' and 'B'
swap_dict_values(my_dict, 'A', 'B')
print("After swapping A and B:", my_dict)
Original dictionary: {'A': 1, 'B': 2, 'C': 3, 'D': 4}
After swapping A and B: {'A': 2, 'B': 1, 'C': 3, 'D': 4}
Method 2: Creating a Copy (Immutable Approach)
This approach preserves the original dictionary by creating a copy ?
def swap_dict_values_copy(dictionary, key1, key2):
"""Return a new dictionary with swapped values"""
swapped_dict = dictionary.copy()
if key1 in swapped_dict and key2 in swapped_dict:
swapped_dict[key1], swapped_dict[key2] = swapped_dict[key2], swapped_dict[key1]
return swapped_dict
else:
print("One or both keys not found")
return dictionary
# Example usage
original_dict = {'name': 'Alice', 'age': 25, 'city': 'NYC'}
print("Original:", original_dict)
new_dict = swap_dict_values_copy(original_dict, 'name', 'age')
print("Original after operation:", original_dict)
print("New dictionary:", new_dict)
Original: {'name': 'Alice', 'age': 25, 'city': 'NYC'}
Original after operation: {'name': 'Alice', 'age': 25, 'city': 'NYC'}
New dictionary: {'name': 25, 'age': 'Alice', 'city': 'NYC'}
Method 3: Using Temporary Variable
Traditional approach using a temporary variable for clarity ?
def swap_with_temp(dictionary, key1, key2):
"""Swap values using temporary variable"""
if key1 in dictionary and key2 in dictionary:
temp = dictionary[key1]
dictionary[key1] = dictionary[key2]
dictionary[key2] = temp
else:
print("Keys not found")
return dictionary
# Example usage
data = {'x': 10, 'y': 20, 'z': 30}
print("Before swap:", data)
swap_with_temp(data, 'x', 'z')
print("After swapping x and z:", data)
Before swap: {'x': 10, 'y': 20, 'z': 30}
After swapping x and z: {'x': 30, 'y': 20, 'z': 10}
Error Handling Example
Robust implementation with proper error handling ?
def safe_swap_dict(dictionary, key1, key2):
"""Safely swap dictionary values with error handling"""
try:
if key1 not in dictionary:
raise KeyError(f"Key '{key1}' not found in dictionary")
if key2 not in dictionary:
raise KeyError(f"Key '{key2}' not found in dictionary")
dictionary[key1], dictionary[key2] = dictionary[key2], dictionary[key1]
return True
except KeyError as e:
print(f"Error: {e}")
return False
# Test with valid keys
test_dict = {'apple': 5, 'banana': 3, 'orange': 8}
print("Original:", test_dict)
if safe_swap_dict(test_dict, 'apple', 'banana'):
print("Swap successful:", test_dict)
# Test with invalid key
safe_swap_dict(test_dict, 'apple', 'grape')
Original: {'apple': 5, 'banana': 3, 'orange': 8}
Swap successful: {'apple': 3, 'banana': 5, 'orange': 8}
Error: Key 'grape' not found in dictionary
Comparison of Methods
| Method | Modifies Original? | Memory Usage | Best For |
|---|---|---|---|
| Tuple Unpacking | Yes | Low | In-place modifications |
| Copy Method | No | Higher | Preserving original data |
| Temporary Variable | Yes | Low | Educational/clarity |
Conclusion
Tuple unpacking is the most efficient and Pythonic way to swap dictionary values. Use the copy method when you need to preserve the original dictionary, and always include error handling for robust applications.
