Sick Gaming
[Tut] How to Get the Key with Maximum Value in a Python Dictionary? - Printable Version

+- Sick Gaming (https://www.sickgaming.net)
+-- Forum: Programming (https://www.sickgaming.net/forum-76.html)
+--- Forum: Python (https://www.sickgaming.net/forum-83.html)
+--- Thread: [Tut] How to Get the Key with Maximum Value in a Python Dictionary? (/thread-94239.html)



[Tut] How to Get the Key with Maximum Value in a Python Dictionary? - xSicKxBot - 03-26-2020

How to Get the Key with Maximum Value in a Python Dictionary?

<div><p>I have spent my morning hours on an important mission. What is the cleanest, fastest, and most concise answer to the following question: How do you find the key with the maximum value in a Python dictionary?  Most answers on the web say you need to use a library but this is not true! </p>
<p><strong>Simply use the max function with the key argument set to <code>dict.get</code></strong>:</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="">income = {'Anne' : 1111, 'Bert' : 2222, 'Cara' : 9999999} print(max(income, key=income.get))
# Cara</pre>
<p>The max function goes over all keys, <code>k</code>, in the dictionary income and takes the one that has maximum value after applying the <code>income.get(k)</code> method. <em>The </em><code>get()</code><em> method returns the value specified for key, </em><code>k</code><em>, in the dictionary.</em></p>
<p>Play with it yourself in our interactive code shell:</p>
<figure><iframe src="https://repl.it/repls/DistinctHalfRate?lite=true" allowfullscreen="true" width="100%" height="600px"></iframe></figure>
<p>Now, read the 4-min article or watch the short video to fully understand this concept.</p>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="How to get the key with the maximum value in a dictionary?" width="1400" height="788" src="https://www.youtube.com/embed/w9IvJvq4Gzc?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<h2 id="max">What’s the Max Function in Python?</h2>
<p> Most likely, you already know <a href="https://blog.finxter.com/integer-and-float-maximums-in-pythons-max-function/">Python’s max(…) function</a>. You can use it to find the maximum value of any iterable or any number of values. Here are a few examples using the max function without specifying any optional arguments. </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=""># Key that starts with 'largest' letter of the alphabet
print(max(income))
# Mary # Largest value in the dictionary income
print(max(income.values()))
# 878000 # Largest value in the given list
print(max([1,4,7,5,3,99,3]))
# 99 # Compare lists element wise, max is first list to have a larger
# element print(max([1,2,3],[5,6,4]))
# [5, 6, 4] # Largest value in the given sequence of numbers
print(max(5,7,99,88,123))
# 123</pre>
<p>So far so good. The max function is very flexible. It works not only for numbers but also for strings, lists, and any other object you can compare against other objects. </p>
<p> Now, let’s look at the optional arguments of the max function. One of them is <code>'key'</code>. Let’s find out what it does. </p>
<h2 id="key-max">How Does the Key Argument of Python’s max() Function Work?</h2>
<p> The last examples show the intuitive workings of the max function: you pass one or more iterables as positional arguments. </p>
<hr class="wp-block-separator"/>
<p> <strong>Intermezzo</strong><em>: What are iterables? An iterable is an object from which you can get an iterator. An iterator is an object on which you can call the next() method. Each time you call next(), you get the ‘next’ element until you’ve got all the elements from the iterator. For example, Python uses iterators in for loops to go over all elements of a list, all characters of a string, or all keys in a dictionary.</em> </p>
<hr class="wp-block-separator"/>
<p>When you specify the key argument, define a function that returns a value for each element of the iterable. Then each element is compared based on the return value of this function, not the iterable element (the default behavior).</p>
<p>Here is an example:</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="">lst = [2, 4, 8, 16] def inverse(val): return -val print(max(lst))
# 16 print(max(lst, key=inverse))
# 2</pre>
<p>We define a function inverse() that returns the value multiplied by -1. Now, we print two executions of the max() function. The first is the default execution: the maximum of the list [2, 4, 8, 16] is 16. The second uses key. We specify ‘inverse’ as the key function. Python applies this function to all values of [2, 4, 8, 16]. It compares these new values with each other and returns the max. Using the inverse function Python does the following mappings: </p>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td><strong>Original Value</strong></td>
<td> &nbsp;<strong>Value after inverse() applied (basis for max())</strong> </td>
</tr>
<tr>
<td>2</td>
<td>-2</td>
</tr>
<tr>
<td>4</td>
<td>-4</td>
</tr>
<tr>
<td>8</td>
<td>-8</td>
</tr>
<tr>
<td>16</td>
<td>-16</td>
</tr>
</tbody>
</table>
</figure>
<p>Python calculates the maximum based on these mappings. In this case, the value 2 (with mapping -2) is the maximum value because -2 &gt; -4 &gt; -8 &gt; -16.&nbsp; </p>
<p>Now let’s come back to the initial question:</p>
<h2 id="key-max-2">How to Get the Key with the Maximum Value in a Dictionary?</h2>
<p>We use the same example as above. The dictionary stores the income of three persons John, Mary, and Alice. Suppose you want to find the person with the highest income. In other words, what is the key with the maximum value in the dictionary?</p>
<p>Now don’t confuse the dictionary key with the optional key argument of the <code>max()</code> function. They have nothing in common – it’s just an unfortunate coincidence that they have the same name!</p>
<p>From the problem, we know the result is a dictionary key. So, we call max() on the keys of the dictionary. Note that <code>max(income.keys())</code> is the same as <code>max(income)</code>. To learn more about dictionaries, check out our article <a href="https://blog.finxter.com/python-dictionary/">Python Dictionary – The Ultimate Guide</a>.</p>
<p>However, we want to compare dictionary values, not keys. We’ll use the key argument of <code>max()</code> to do this. We must pass it a function but which?&nbsp;</p>
<p>To get the value of <code>'Anne'</code>, we can use bracket notation – <code>income['Anne']</code>. But bracket notation is not a function, so that doesn’t work. Fortunately, <code>income.get(‘Anne’)</code> does (almost) the same as <code>income['Anne']</code> and it is a function! The only difference is that it returns <code>None</code> if they key is not in the dictionary. So we’ll pass that to the key argument of <code>max()</code>. </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="">income = {'Anne' : 1111, 'Bert' : 2222, 'Cara' : 9999999} print(max(income, key=income.get))
# Cara</pre>
<h2 id="key-min">How to Get the Key with the Minimum Value in a Dictionary?</h2>
<p>If you understood the previous code snippet, this one will be easy. To find the key with minimum value in the dictionary we use the min() function. </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="">income = {'Anne' : 1111, 'Bert' : 2222, 'Cara' : 9999999} print(min(income, key=income.get))
# Anne</pre>
<p>The only difference is that we use the built-in min() function instead of the built-in max() function. That’s it.</p>
<h2 id="alternatives"> Find the Key with the Max Value in a Dictionary – Alternative Methods </h2>
<p>There are lots of different ways to solve this problem. They are not as beautiful or clean as the above method. But, for completeness, let’s explore some more ways of achieving the same thing.</p>
<p>In a <a href="https://stackoverflow.com/questions/268272/getting-key-with-maximum-value-in-dictionary">StackOverflow answer</a>, a user compared nine (!) different methods to find the key with the maximum value in a dictionary. Here they are:</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=""># Convert to lists and use .index(max())
def f1(): v=list(income.values()) k=list(income.keys()) return k[v.index(max(v))] # Dictionary comprehension to swap keys and values
def f2(): d3={v:k for k,v in income.items()} return d3[max(d3)] # Use filter() and a lambda function
def f3(): return list(filter(lambda t: t[1]==max(income.values()), income.items()))[0][0] # Same as f3() but more explicit
def f4(): m=max(income.values()) return list(filter(lambda t: t[1]==m, income.items()))[0][0] # List comprehension
def f5(): return [k for k,v in income.items() if v==max(income.values())][0] # same as f5 but remove the max from the comprehension
def f6(): m=max(income.values()) return [k for k,v in income.items() if v==m][0] # Method used in this article
def f7(): return max(income,key=income.get) # Similar to f1() but shortened to 2 lines
def f8(): v=list(income.values()) return list(income.keys())[v.index(max(v))] # Similar to f7() but use a lambda function
def f9(): return max(income, key=lambda k: income[k]) print(f1())
print(f2())
print(f3())
print(f4())
print(f5())
print(f6())
print(f7())
print(f8())
print(f9())
# Cara (all outputs)</pre>
<p> In a <a href="https://stackoverflow.com/questions/268272/getting-key-with-maximum-value-in-dictionary">benchmark </a>performed on a large dictionary by the StackOverflow user, f1() turned out to be the fastest one. </p>
<p><strong> So the second best way to get the key with the maximum value from a dictionary is: </strong></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="">income = {'Anne' : 1111, 'Bert' : 2222, 'Cara' : 9999999} v=list(income.values())
k=list(income.keys())
print(k[v.index(max(v))])
# Cara</pre>
<h2>Find Key with Longest Value in Dictionary </h2>
<p>We know how to find the maximum value if the values are numbers. What about if they are lists or strings?</p>
<p>Let’s say we have a dictionary that records the number of days each person worked this month. If they worked a day, we append 1 to that person’s list. If they didn’t work, we don’t do anything.&nbsp; At the end of the month, our dictionary looks like this. </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="">days_worked = {'Anne': [1, 1, 1, 1], 'Bert': [1, 1, 1, 1, 1, 1], 'Cara': [1, 1, 1, 1, 1, 1, 1, 1]}</pre>
<p>The total number of days worked each month is the length of each list. If all elements of two lists are the same (as is the case here), they are compared based on their length. </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=""># Length 2 is less than length 4
>>> [1, 1] &lt; [1, 1, 1, 1]
True</pre>
<p>So we can use the same code we’ve been using in the article to find the key with the maximum value. </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="">>>> max(days_worked, key=days_worked.get) 'Cara'</pre>
<p> If we update our dictionary so that Bert has worked the most days and apply max() again, Python returns ‘Bert’. </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="">>>> days_worked = {'Anne': [1, 1, 1, 1], 'Bert': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 'Cara': [1, 1, 1, 1, 1, 1, 1, 1]} # Bert has now worked the most
>>> max(days_worked, key=days_worked.get)</pre>
<h2> Find Key With Max Value in a List of Dictionaries </h2>
<p> Let’s say we have 3 dictionaries containing income information. We want to find the key with the max value from all 3 dictionaries.&nbsp; </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="">income1 = {'Anne': 1111, 'Bert': 2222, 'Cara': 3333} income2 = {'Dani': 4444, 'Ella': 5555, 'Fred': 6666} income3 = {'Greg': 7777, 'Hope': 8888, 'Igor': 999999999999} list_of_dicts = [income1, income2, income3]</pre>
<p>We can see that ‘Igor’ has the highest income so we expect that to be returned. </p>
<p>There are several ways to do this. The simplest is to put all key-value pairs into one dictionary using a for loop. Then we call max() as usual.</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=""># Initialise empty dict
>>> big_dict = {} # Use for loop and .update() method to add the key-value pairs
>>> for dic in list_of_dicts: big_dict.update(dic) # Check the result is as expected
>>> big_dict
{'Anne': 1111, 'Bert': 2222, 'Cara': 3333, 'Dani': 4444, 'Ella': 5555, 'Fred': 6666, 'Greg': 7777, 'Hope': 8888, 'Igor': 999999999999} # Call max() and specify key argument
>>> max(big_dict, key=big_dict.get) 'Igor' </pre>
<h2>Where to Go From Here?</h2>
<p>Every Python master must know the basics. Improving your basic code understanding skills by 20% will improve your productivity by much more than anything else. Why? Because everything else builds upon the basics.</p>
<p>But most material online is tedious and boring. That’s why I’ve written a new and exciting way of learning Python, while measuring and comparing your skills against other coders. Check out the book “Coffee Break Python”. It’s LeanPub 2019 bestseller in the category Python!</p>
<div class="wp-block-button aligncenter is-style-default"><a class="wp-block-button__link has-background has-vivid-red-background-color" href="https://blog.finxter.com/coffee-break-python/">Get Your Coffee Break Python Now</a></div>
</div>


https://www.sickgaming.net/blog/2020/03/23/how-to-get-the-key-with-maximum-value-in-a-python-dictionary/