Swap keys with values and Vice Versa of a dictionary in Python
To swap a dictionary with values replace by keys and keys replaced by values, we can done using
- Swap key value of a dictionary
for
loop - Swap key value of a dictionary using dictionary comprehension
Swapping key value pair of a dictionary using for loop in Python
We will see how to swap a key value pair of a dictionary using for
loop in the following code snippet using python.
d1 = {'Bob': 60, 'Alice': 43, 'Ram': 80, 'Geeta': 49, 'Shreyan': 95, 'Raj': 68}
print('Before Swap')
print(d1)
swapped_d1 = dict()
for k, v in d1.items():
swapped_d1[v] = k
print('After Swap')
print(swapped_d1)
In the preceding code, we see that we are iterating over dictionary's items()
using for
loop. We are then creating a new dictionary with the values as keys and keys as values.
Before Swap
{'Bob': 60, 'Alice': 43, 'Ram': 80, 'Geeta': 49, 'Shreyan': 95, 'Raj': 68}
After Swap
{60: 'Bob', 43: 'Alice', 80: 'Ram', 49: 'Geeta', 95: 'Shreyan', 68: 'Raj'}
Swapping key value pair of a dictionary using dictionary comprehension in Python
We will see how to swap a key value pair of a dictionary using dictionary comprehension in the following code snippet using python.
d1 = {'Bob': 60, 'Alice': 43, 'Ram': 80, 'Geeta': 49, 'Shreyan': 95, 'Raj': 68}
print('Before Swap')
print(d1)
swapped_d1 = {value:key for key, value in d1.items()}
print('After Swap')
print(swapped_d1)
The output after swapping the keys of a dictionary with values and values with respective keys using dictionary comprehension will appear as follows.
Before Swap
{'Bob': 60, 'Alice': 43, 'Ram': 80, 'Geeta': 49, 'Shreyan': 95, 'Raj': 68}
After Swap
{60: 'Bob', 43: 'Alice', 80: 'Ram', 49: 'Geeta', 95: 'Shreyan', 68: 'Raj'}
Swap key value pair with duplicate values of a dictionary in Python
It is noteworthy to observe that when a dictionary with repeated value is swapped by any of the aforementioned methods, will lead to the most latest key preserved in the resulting dictionary.
For example, consider the following dictionary
fruit_dict = {1: 'Apple', 2: 'Apple', 3: 'Orange', 4: 'Peach'}
swapped_fruit_dict = {value:key for key, value in fruit_dict.items()}
print('Before Swap')
print(fruit_dict)
print('After Swap')
print(swapped_fruit_dict)
Let's observe the output before and after the Swap of the key value pair whose dictionary before swapping has duplicate values.
Before Swap
{1: 'Apple', 2: 'Apple', 3: 'Orange', 4: 'Peach'}
After Swap
{'Apple': 2, 'Orange': 3, 'Peach': 4}
From the preceding output, we notice that before swap, we had two keys viz., 1 and 2 in our original dictionary fruit_dict whose value is Apple.
Where as in the swapped dictionary, the latest occurrence of the value Apple whose is 2 in the original dictionary is preserved in the resultant swapped_fruit_dict.