Swap position of two values python dictionary is exchanging values of two keys inside a python dictionary either via looping over the dict or reconstructing the dict. To demonstrate all these techniques for swapping the values, we will create a sample dummy dict object. We will use the same object in each method of solving, So let’s start.
Swap position of two values python dictionary ( Solution )-
Let’s create a dummy dictionary in python with some values.
sample_dict={'A':1,'B':2,'C':3,'D':4,'E':5}
print(type(sample_dict))
Solution 1: Index-based Swapping –
Suppose you want to swap the value of the second key with the value of the first index key. To achieve this we need to follow the below steps.
1. Extract all the keys and values from the dictionary into the list data structure.
2. Now swap the values in the list on the basis of the required swapping index.
3. recreate the dict using the list of keys and values via a loop.
Here is the complete code for the same.
sample_dict={'A':1,'B':2,'C':3,'D':4,'E':5}
print(type(sample_dict))
keys=list(sample_dict.keys())
values=list(sample_dict.values())
i=1
j=2
temp =values[i]
values[i]=values[j]
values[j]=temp
for ele in range(len(values)):
sample_dict[keys[ele]]=values[ele]
print(sample_dict)

Solution 2: Key-based swapping –
Suppose you exactly know which key, you want to perform the swapping of values then you need to use assignment interchange. It will be easier to look at the code and understand it. Considering the same above sample_dict for example. Here we will swap the value of key ‘A’ and Key ‘B’. Below is the code for key-based swapping.
sample_dict['A'],sample_dict['B'] =sample_dict['B'] , sample_dict['A']

Bonus – Swapping items order in the dictionary :
In case you want to swap the order of both key and value in the dict. Then use the below trick which is identical conceptually to the above method of swapping using the index.
sample_dict={'A':1,'B':2,'C':3,'D':4,'E':5}
t = list(sample_dict.items())
i=0
j=1 # swapping items in this order
t[i], t[j] = t[j], t[i]
print("Interchanged tuple:", t)
sample_dict = dict(t)
print("Final:", sample_dict)

Thanks
Data Science Learner Team
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.