How to Reverse/Invert a Dictionary Mapping

In Python, a dictionary is an implementation of a data structure known most commonly as an associative array.

This collection of key-values pairs maps the key to the associated value that can be implemented in many ways from knowing the price of apples and peas to put into the grocery store app that is used on your phone all the way to wanting to know which Major League Baseball team belongs in which state! It is a versatile way of finding the information you need, it is mutable, dynamic, and can be nested! Accessing the values in a dictionary means you need to have the key for the proper value to be printed.

Problem: There are times, however when you will need to have the reverse the dictionary. You will not only have to put the last key-value pair in the first index, but you will have to reverse the value and key pairs around inside the dictionary!

As difficult as this sounds it is actually quite simple and we are going to go through 3 different solutions on how this can be done I your code with an explanation on each step. I will write 3 separate pieces of code that will show you how this can be done with various pieces of data that can be used for inverting a dictionaries mapping.

In this first example, I am going to use an everyday dictionary for the prices of fruits at the local super-market. I am going to use a for loop to iterate through my dictionary and switch the values with their respective keys. First things first, know what data you are going to be using. In this case, we are getting the prices of fruits to place in our associative array. I am going to use the fruits as my keys and the prices as values.

for_sale = {'Apple': 0.69, 'Coconut': 1.69, 'Tangerine': 0.75, 'Banana': 1.25}

Well this is great! We have our keys and their prices stored in our dictionary for_sale. Now it is time to make a new empty dictionary to place the new keys and values into!

new_sale = {}

Now it is time to iterate through the dictionary and reverse the keys and values! We are going to use a for loop!

for key, value in for_sale.items():
    new_sale[value] = key

Let’s run the new dictionary!

print(new_sale)

Here is the new outcome!

{0.69: 'Apple', 1.69, 'Coconut', 0.75:'Tangerine', 1.25:'Banana'}

Now, lets put the entire code together!

for_sale ={'Apple': 0.69, 'Coconut': 1.69,'Tangerine': 0.75, 'Banana': 1.25}
new_sale = {}

for key, value in for_sale.items():
    new_sale[value] = key

print(new_sale)
# {0.69: 'Apple', 1.69: 'Coconut', 0.75: 'Tangerine', 1.25: 'Banana'}

There! That is all it took! This is a simple 8 lines way to get this done. The expression new_sale[value] = key, did all the hard work for you! Please note that this does not sort your dictionary! It only reverses the key and values around! Starting from the top of our code, we can see that our dictionary has the fruits in the keys and the prices in the values. We created an empty list to place the new dictionary. After we walked through the dictionary, switching the key and value pairs around for each instance of a pair. We, then asked the dictionary to run with its new name. The new dictionary now has the prices as the keys and the fruits as the values! There is one small problem with this 8 small lines of code, however. As beautifully as it works, it’s messy and marks you as a beginner.

In Python, we want beautiful pythonic code that is easy to comprehend and does not take up too many lines in our code especially since we just need to change around the key-value pairs! So, the best thing to use is a dictionary comprehension approach. Knowing how to work a dictionary comprehensively is not only a testament to your skills but will also make it easier when you want to insert a couple lines of code to make a correction without having to rewrite parts of your code. What is dictionary comprehension, you may wonder? Well, it is a very useful feature if you would like to construct a dictionary in one line of code! This reduces your dictionary to a single line, saving space and memory in your code. Using the {key:value} mapping directly from an iterable object, like a list we can construct our dictionary, even use conditional statements!

In this next example, we are going to use a one-liner to do what we did above. This time we are going to use the pet store and find out the prices of some small pets to buy! We are going to use the pets as our keys and prices again for the values.

small_pets = {'Goldfish':0.50, 'Gerbil':1.0, 'Parakeet':2}

In the next line, I will use a dictionary comprehensive approach to reverse the values for the keys:

inverted_pets = {values: key for key, value in dict.items(small_pets)}

Then I will print the new dictionary:

print(inverted_pets)

And my outcome is:

inverted_pets = {0.5:'Goldfish', 1.0:'Gerbil', 2:'Parakeet'}

Now let us walk through this step by step. I created a dictionary called small_pets. Next, I created a new dictionary, inverted_pets and at the same time asked it to go through each item in the dictionary, and switch the values for the keys in the dictionary small_pets. On the following line, I asked it to print the new dictionary. Now to put it all together!

small_pets = {'Goldfish':0.50, 'Gerbil':1.0, 'Parakeet':2}
inverted_pets = {values: key for key, value in dict.items(small_pets)}

print(inverted_pets)
# Outcome: {0.5:'Goldfish', 1.0:'Gerbil', 2:'Parakeet'}

When using this method, remember to pass in the argument in the new dictionary. Without it, your program will break and you will get an error telling you that dict.items() takes a positional argument and there are none given. Now this bit of code is much cleaner then the first one we wrote! It took 5 less lines than the previous code and it still gets the job done! This is a hallmark of a Pythonier who knows what he/she is doing in the real world! As you can see here again, this method does not sort the dictionary, just reverses the order of the key-value pairs. Yet a third way, to accomplish your goal of inversing a value for its key in a dictionary is 3 lines!

small_pets = {'Goldfish':0.69, 'Gerbil':1.5, 'Parakeet':2}
d = {v:[i for i in small_pets.keys() if small_pets[i] == v ] for k,v in small_pets.items()}
print(d)
# {0.69: ['Goldfish'], 1.5: ['Gerbil'], 2: ['Parakeet']}

As you can see by the method above this code is a bit longer than its predecessor, but it allows Python to be used in a very dynamic way showing the use of conditionals inside the dictionary construction and increasing the confusion as the dictionary small_pets is used several times. Be careful using this method if you are a beginner or just getting comfortable in dictionaries. If you wanted to you could rename the same dictionary to the same name as you are inverting the old one by its values and keys. These 3 examples are ones I was able to comprehend and write code based off of it. However, there are many ways to find your answers in Python and write out your code to fit your needs. I would say make sure you are comfortable working in dictionaries before trying anything outside your comfort zone. I would also say that it is better not to copy paste the first code you come across. This can break your program and make it hard to revert back to its original form and get it working properly again. Make sure to label your variable correctly and your program should work reversing the keys and their values!

Resources

I found my information on StackOverflow for writing my code with the link I used posted below. I also added the link to Real Python for iteration in dictionaries and turning keys in values and the link to one of my favorite resources: AskPython. As a Python junior developer, I find it crucial to have as many great resources as possible, just like Finxter to help me continue to learn and grow! I hope you will also see the value in these resources and more and I encourage you to seek them out, join up and upskill yourself! I know a certainly could not have found the information I need to write code if I didn’t have the resources that I do!