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.
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.
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.
The output after swapping the keys of a dictionary with values and values with respective keys using dictionary comprehension will appear as follows.
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
Let's observe the output before and after the Swap of the key value pair whose dictionary before swapping has duplicate values.
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.