Kodeclik Blog
How to swap positions of values in a Python dictionary
In this blogpost we will learn how to swap positions of values in a Python dictionary. Let us first create a Python dictionary:
mydict = {'Apples': 3, 'Oranges': 2, 'Bananas': 6}
print(mydict)
In the above code we have created a dictionary where the keys are names of fruits and the values are prices of the fruits. Thus Apples cost $3, Oranges cost $2, and so on.
The output of the above two lines of code is:
{'Apples': 3, 'Oranges': 2, 'Bananas': 6}
Let us now suppose the cost of Oranges has gone up (due to a bad season in Florida) and that the cost of Apples has gone down. So we would like to swap the values (ie prices) of these two fruits. One way to do it is to completely rewrite the dictionary creation line but that is too cumbersome. We will learn how to swap the positions of the values.
The bad way to swap two values in a Python dictionary
If we are used to other programming languages, you will likely do something like this, i.e., first storing one dictionary value in a temporary variable and then using this to swap the value, like so:
mydict = {'Apples': 3, 'Oranges': 2, 'Bananas': 6}
print(mydict)
temp = mydict['Apples']
mydict['Apples'] = mydict['Oranges']
mydict['Oranges'] = temp
print(mydict)
The output of the code is:
{'Apples': 3, 'Oranges': 2, 'Bananas': 6}
{'Apples': 2, 'Oranges': 3, 'Bananas': 6}
Note how the positions of the 2 and 3 have been swapped (but the position of 6 stays the same).
The Pythonic way to swap two values in a Python dictionary
While the above code works, it is not a very elegant way to achieve the goal. Here is how you swap two values in a Python dictionary in a more Python-ic way.
mydict = {'Apples': 3, 'Oranges': 2, 'Bananas': 6}
print(mydict)
mydict['Apples'], mydict['Oranges'] = mydict['Oranges'], mydict['Apples']
print(mydict)
Notice how in the third line, in the assignment statement we have two values listed on both the left and right side (but in different orders). The output of the code is the same as before:
{'Apples': 3, 'Oranges': 2, 'Bananas': 6}
{'Apples': 2, 'Oranges': 3, 'Bananas': 6}
Swapping positions of two values when only the values are given
A more complicated scenario is when you have the values given (like 3 and 2 in our case) and you desire to swap them. Now this is more complicated. You first have to find the positions (i.e., indices) where these two values can be found and then use the above code to swap the values at these positions.
Let us first write a function to retrieve the position (i.e., index) given the value. Here is how such a function can look like:
def find_key_given_value(dict,val):
keylist = list(dict.keys())
valuelist = list(dict.values())
return (keylist[valuelist.index(val)])
The function “find_key_given_value” takes two inputs: a dictionary (dict) and a value (val). We first create a list (called keylist) containing all the keys of the dictionary (using the list constructor to construct the said list). Then we create a list called valuelist containing all the values of the dictionary. Finally, we find the location of the desired value in the “valuelist” list (using the index method) and then with that returned location look up the key in the keylist, and return that key.
Now we are ready to roll! Here is the full code containing the above function as well as driver code:
def find_key_given_value(dict,val):
keylist = list(dict.keys())
valuelist = list(dict.values())
return (keylist[valuelist.index(val)])
# initialize the dictionary as before
mydict = {'Apples': 3, 'Oranges': 2, 'Bananas': 6}
# print the dictionary
print(mydict)
# we seek to swap the values 2 and 3
# so let us first find positions of 2 and 3
pos_2 = find_key_given_value(mydict,2)
pos_3 = find_key_given_value(mydict,3)
# swap the values at these two positions
mydict[pos_2], mydict[pos_3] = mydict[pos_3], mydict[pos_2]
# print the dictionary again
print(mydict)
In the above code, after defining the function, we initialize the dictionary as before, and use the function to find where the values 2 and 3 are stored. This returns two keys (which in our case will be ‘Apples’ and ‘Oranges’). Then we swap them in the usual Pythonic notation.
The output is as expected:
{'Apples': 3, 'Oranges': 2, 'Bananas': 6}
{'Apples': 2, 'Oranges': 3, 'Bananas': 6}
We have learnt how to swap positions of two values in a Python dictionary. For more fun with Python dictionaries, checkout our blogposts on initializing a Python dictionary and finding the length of a Python dictionary.
Once you are comfortable with dictionaries, learn how to increment a value in a Python dictionary, and how to find the first key in a Python dictionary.
If you like learning innovative ways to swap variables, checkout our blogpost on how to swap variables in Javascript.
For more Python content, checkout the math.ceil() and math.floor() functions! Also
learn about the math domain error in Python and how to fix it!
Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.