Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Reverse/Invert a Dictionary Mapping

#1
How to Reverse/Invert a Dictionary Mapping

<div><p>In Python, a <a href="https://blog.finxter.com/python-dictionary/" target="_blank" rel="noreferrer noopener" title="Python Dictionary – The Ultimate Guide">dictionary </a>is an implementation of a data structure known most commonly as an associative array. </p>
<p>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. </p>
<p><strong>Problem</strong>: 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!</p>
<p>As difficult as this sounds it is actually quite simple and we are going to go through <strong>3 different solutions</strong> 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.</p>
<p>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<a href="https://blog.finxter.com/python-loops/" target="_blank" rel="noreferrer noopener" title="Python Loops"> for loop</a> 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 <em>prices</em> of <em>fruits</em> to place in our associative array. I am going to use the fruits as my keys and the prices as values.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">for_sale = {'Apple': 0.69, 'Coconut': 1.69, 'Tangerine': 0.75, 'Banana': 1.25}</pre>
<p>Well this is great! We have our keys and their prices stored in our dictionary <em><code>for_sale</code></em>. Now it is time to make a new <strong>empty</strong> dictionary to place the new keys and values into!</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">new_sale = {}</pre>
<p>Now it is time to iterate through the dictionary and reverse the keys and values! We are going to use a for loop!</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">for key, value in for_sale.items(): new_sale[value] = key</pre>
<p>Let’s run the new dictionary!</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">print(new_sale)</pre>
<p>Here is the new outcome!</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">{0.69: 'Apple', 1.69, 'Coconut', 0.75:'Tangerine', 1.25:'Banana'}</pre>
<p>Now, lets put the entire code together!</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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'}</pre>
<p>There! That is all it took! This is a simple 8 lines way to get this done. The expression <em>new_sale[value] = key</em>, did all the hard work for you! Please note that this does not <a href="https://blog.finxter.com/daily-python-puzzle-how-to-sort-dictionaries-python/" target="_blank" rel="noreferrer noopener" title="How to Sort Dictionaries in Python?"><strong>sort</strong> your dictionary</a>! 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 <a href="https://blog.finxter.com/how-to-create-a-python-list/" target="_blank" rel="noreferrer noopener" title="How to Create a Python List?">created an empty list </a>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 <em>prices</em> as the keys and the <em>fruits</em> 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. </p>
<p>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 <a href="https://blog.finxter.com/python-dictionary-comprehension/" target="_blank" rel="noreferrer noopener" title="Python Dictionary Comprehension: A Powerful One-Liner Tutorial">dictionary comprehension</a> 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 <code>{key:value}</code> mapping directly from an iterable object, like a list we can construct our dictionary, even use <a href="https://blog.finxter.com/python-one-line-conditional-assignment/" target="_blank" rel="noreferrer noopener" title="Python One Line Conditional Assignment">conditional </a>statements!</p>
<p>In this next example, we are going to use a <a href="https://blog.finxter.com/python-one-liners/" target="_blank" rel="noreferrer noopener" title="56 Python One-Liners to Impress Your Friends">one-liner</a> 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.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">small_pets = {'Goldfish':0.50, 'Gerbil':1.0, 'Parakeet':2}</pre>
<p>In the next line, I will use a dictionary comprehensive approach to <a href="https://blog.finxter.com/how-to-reverse-a-list-in-python/" target="_blank" rel="noreferrer noopener" title="How to Reverse a List in Python?">reverse </a>the values for the keys:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">inverted_pets = {values: key for key, value in dict.items(small_pets)}</pre>
<p>Then I will print the new dictionary:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">print(inverted_pets)</pre>
<p>And my outcome is:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">inverted_pets = {0.5:'Goldfish', 1.0:'Gerbil', 2:'Parakeet'}</pre>
<p>Now let us walk through this step by step. I created a dictionary called<em> small_pets</em>. Next, I created a new dictionary, <em>inverted_pets</em> 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 <em>small_pets</em>. On the following line, I asked it to print the new dictionary. Now to put it all together!</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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'}
</pre>
<p>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 <em>dict.items()</em> 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!</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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']}</pre>
<p>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 <em>small_pets </em>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!</p>
<h2>Resources</h2>
<p>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!</p>
<ul>
<li><a href="https://stackoverflow.com/questions/483666/reverse-invert-a-dictionary-mapping" target="_blank" rel="noreferrer noopener">https://stackoverflow.com/questions/483666/reverse-invert-a-dictionary-mapping</a></li>
<li><a href="https://realpython.com/iterate-through-dictionary-python/#turning-keys-into-values-and-vice-versa" target="_blank" rel="noreferrer noopener">https://realpython.com/iterate-through-dictionary-python/#turning-keys-into-values-and-vice-versa</a></li>
<li><a href="https://www.askpython.com/python/dictionary/python-dictionary-comprehension" target="_blank" rel="noreferrer noopener">https://www.askpython.com/python/dictionary/python-dictionary-comprehension</a></li>
</ul>
<p>The post <a href="https://blog.finxter.com/how-to-reverse-invert-a-dictionary-mapping/" target="_blank" rel="noopener noreferrer">How to Reverse/Invert a Dictionary Mapping</a> first appeared on <a href="https://blog.finxter.com/" target="_blank" rel="noopener noreferrer">Finxter</a>.</p>
</div>


https://www.sickgaming.net/blog/2020/12/...y-mapping/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016