Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Find the Most Common Element in a Python Dictionary

#1
How to Find the Most Common Element in a Python Dictionary

<div>
<div class="kk-star-ratings kksr-auto kksr-align-left kksr-valign-top" data-payload="{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;647962&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;ignore&quot;:&quot;&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;class&quot;:&quot;&quot;,&quot;count&quot;:&quot;1&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;5&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;5\/5 - (1 vote)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;width&quot;:&quot;142.5&quot;,&quot;_legend&quot;:&quot;{score}\/{best} - ({count} {votes})&quot;,&quot;font_factor&quot;:&quot;1.25&quot;}">
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 142.5px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend" style="font-size: 19.2px;"> 5/5 – (1 vote) </div>
</div>
<h2 class="wp-embed-aspect-16-9 wp-has-aspect-ratio">Problem Formulation and Solution Overview</h2>
<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">This article will show you how to find the most common element in a Python <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary/" data-type="URL" data-id="https://blog.finxter.com/python-dictionary/" target="_blank">Dictionary</a>. However, since all <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary/" data-type="URL" data-id="https://blog.finxter.com/python-dictionary/" target="_blank">Dictionary</a> Keys are unique, this article focuses on searching for the most common <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary/" data-type="URL" data-id="https://blog.finxter.com/python-dictionary/" target="_blank">Dictionary</a> Value.</p>
<p>To make it more fun, we have the following running scenario:</p>
<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio"><em>Marty Smart, a Math Teacher at Harwood High, has amassed his student’s grades for the semester and has come to you to write a script to determine the most common grade. <em>Below is sample data.</em></em></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">students = {'Marc': 99, 'Amie': 76, 'Jonny': 98, 'Anne': 99, 'Andy': 77, 'Elli': 98, 'Acer': 67, 'Joan': 61, 'Mike': 54, 'Anna': 76, 'Bobi': 67, 'Kate': 99, 'Todd': 98, 'Emma': 49, 'Stan': 76, 'Harv': 99, 'Ward': 67, 'Hank': 54, 'Wendy': 98, 'Sven': 100}</pre>
<hr class="wp-block-separator has-alpha-channel-opacity wp-embed-aspect-16-9 wp-has-aspect-ratio"/>
<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio has-global-color-8-background-color has-background"><em><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4ac.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Question</strong>: How would we write code to </em>locate the most common value in a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary/" data-type="URL" data-id="https://blog.finxter.com/python-dictionary/" target="_blank">Dictionary</a><em>?</em></p>
<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">We can accomplish this task by one of the following options:</p>
<ul type="video" class="wp-embed-aspect-16-9 wp-has-aspect-ratio">
<li><strong>Method </strong>1: Use <code><a rel="noreferrer noopener" href="https://docs.python.org/3/library/statistics.html" data-type="URL" data-id="https://docs.python.org/3/library/statistics.html" target="_blank">statistics.mode()</a></code></li>
<li><strong>Method </strong>2: Use <a rel="noreferrer noopener" href="https://docs.python.org/3/library/collections.html" data-type="URL" data-id="https://docs.python.org/3/library/collections.html" target="_blank"><code>collections.Counter</code></a></li>
<li><strong>Method </strong>3: Use <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" data-type="URL" data-id="https://blog.finxter.com/python-loops/" target="_blank">for</a></code> loop and <a rel="noreferrer noopener" href="https://blog.finxter.com/python-max/" data-type="URL" data-id="https://blog.finxter.com/python-max/" target="_blank"><code>max()</code></a></li>
<li><strong>Method 4</strong>: Use <a rel="noreferrer noopener" href="https://blog.finxter.com/python-max/" data-type="URL" data-id="https://blog.finxter.com/python-max/" target="_blank"><code>max()</code></a></li>
</ul>
<hr class="wp-block-separator has-alpha-channel-opacity"/>
<h2>Method 1: Use statistics mode()</h2>
<p class="has-global-color-8-background-color has-background">This example uses <a rel="noreferrer noopener" href="https://docs.python.org/3/library/statistics.html" data-type="URL" data-id="https://docs.python.org/3/library/statistics.html" target="_blank"><code>mode()</code></a> from the <a rel="noreferrer noopener" href="https://docs.python.org/3/library/statistics.html" data-type="URL" data-id="https://docs.python.org/3/library/statistics.html" target="_blank"><code>statistics</code></a> library. This function returns the single most common element found in the passed argument.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from statistics import mode
common_val = mode(students.values())</pre>
<p>The above code calls in <a rel="noreferrer noopener" href="https://docs.python.org/3/library/statistics.html" data-type="URL" data-id="https://docs.python.org/3/library/statistics.html" target="_blank"><code>mode()</code></a> from the statistics library.</p>
<p>The following line uses the <a rel="noreferrer noopener" href="https://docs.python.org/3/library/statistics.html" data-type="URL" data-id="https://docs.python.org/3/library/statistics.html" target="_blank"><code>mode()</code></a> function and passes the <em>values</em> from the <em>key:value</em> pair of <code>students</code> as an argument. The results save to <code>common_val</code>.</p>
<p>If the contents of <code>students.values()</code> are output to the terminal, the following will display.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">print(students.values())</pre>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td><code>dict_values([99, 76, 98, 99, 77, 98, 67, 61, 54, 76, 67, 99, 98, 49, 76, 99, 67, 54, 98, 100])</code></td>
</tr>
</tbody>
</table>
</figure>
<p>Run the code below to find the most common value.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">print(common_val)</pre>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td>99</td>
</tr>
</tbody>
</table>
</figure>
<p>This is correct!</p>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube"><a href="https://blog.finxter.com/how-to-find-the-most-common-element-in-a-dictionary/"><img src="https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FqX0qqEVpP5s%2Fhqdefault.jpg" alt="YouTube Video"></a><figcaption></figcaption></figure>
<hr class="wp-block-separator has-alpha-channel-opacity"/>
<h2>Method 2: Use Collections.Counter</h2>
<p class="has-global-color-8-background-color has-background">This example uses the <a rel="noreferrer noopener" href="https://docs.python.org/3/library/collections.html" data-type="URL" data-id="https://docs.python.org/3/library/collections.html" target="_blank"><code>collections</code></a> library with the <a rel="noreferrer noopener" href="https://docs.python.org/3/library/collections.html#collections.Counter" data-type="URL" data-id="https://docs.python.org/3/library/collections.html#collections.Counter" target="_blank"><code>counter()</code></a> function to keep track of each element count.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from collections import Counter common_val = Counter(students.values()).most_common</pre>
<p>The above code imports Python’s built-in <a rel="noreferrer noopener" href="https://docs.python.org/3/library/collections.html" data-type="URL" data-id="https://docs.python.org/3/library/collections.html" target="_blank"><code>collections</code></a> library and <a rel="noreferrer noopener" href="https://docs.python.org/3/library/collections.html#collections.Counter" data-type="URL" data-id="https://docs.python.org/3/library/collections.html#collections.Counter" target="_blank"><code>counter()</code></a>. </p>
<p>Next, the <a rel="noreferrer noopener" href="https://docs.python.org/3/library/collections.html#collections.Counter" data-type="URL" data-id="https://docs.python.org/3/library/collections.html#collections.Counter" target="_blank"><code>counter()</code></a> function is called and is passed all <em>values</em> from the <em>key:value</em> pair of <code>students</code> as an argument. Then, <a rel="noreferrer noopener" href="https://docs.python.org/3/library/collections.html" data-type="URL" data-id="https://docs.python.org/3/library/collections.html" target="_blank"><code>most_common()</code></a> is appended. The results save to <code>common_val</code>.</p>
<p>If this was output to the terminal, the following would display.</p>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td><code>&lt;bound method Counter.most_common of Counter({99: 4, 98: 4, 76: 3, 67: 3, 54: 2, 77: 1, 61: 1, 49: 1, 100: 1})></code></td>
</tr>
</tbody>
</table>
</figure>
<p>This isn’t the result we want. How can we get this result?</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">common_val = Counter(students.values()).most_common(1) </pre>
<p>If we append a (1) to the end of most_common, a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" data-type="URL" data-id="https://blog.finxter.com/python-lists/" target="_blank">List</a> containing one <a rel="noreferrer noopener" href="https://blog.finxter.com/the-ultimate-guide-to-python-tuples/" data-type="URL" data-id="https://blog.finxter.com/the-ultimate-guide-to-python-tuples/" target="_blank">Tuple</a> returns.</p>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td><code>[(99, 4)]</code></td>
</tr>
</tbody>
</table>
</figure>
<p>To extract the data further, use slicing (<code>[0])</code> to reference the <a rel="noreferrer noopener" href="https://blog.finxter.com/the-ultimate-guide-to-python-tuples/" data-type="URL" data-id="https://blog.finxter.com/the-ultimate-guide-to-python-tuples/" target="_blank">Tuple</a> and assign the output accordingly.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">value, count = Counter(students.values()).most_common(1)[0]
print(value, count)</pre>
<p>Much clearer! The grade of 99 appears 4 times in <code>students</code>.</p>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td>99 4</td>
</tr>
</tbody>
</table>
</figure>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube"><a href="https://blog.finxter.com/how-to-find-the-most-common-element-in-a-dictionary/"><img src="https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FD2i-SmUELJI%2Fhqdefault.jpg" alt="YouTube Video"></a><figcaption></figcaption></figure>
<hr class="wp-block-separator has-alpha-channel-opacity"/>
<h2>Method 3: Use For Loop and max()</h2>
<p class="has-global-color-8-background-color has-background">This example locates the most common value in a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary/" data-type="URL" data-id="https://blog.finxter.com/python-dictionary/" target="_blank">Dictionary</a> using a <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" data-type="URL" data-id="https://blog.finxter.com/python-loops/" target="_blank">for</a></code> loop and <a rel="noreferrer noopener" href="https://blog.finxter.com/python-max/" data-type="URL" data-id="https://blog.finxter.com/python-max/" target="_blank"><code>max()</code></a> without importing a library.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">tally = {}
for k, v in students.items(): if v not in tally: tally[v] = 0 else: tally[v] += 1
print(max(tally, key=tally.get))</pre>
<p>The above code declares an empty <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary/" data-type="URL" data-id="https://blog.finxter.com/python-dictionary/" target="_blank">Dictionary</a> <code>tally</code>.</p>
<p>Then a <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" data-type="URL" data-id="https://blog.finxter.com/python-loops/" target="_blank">for</a></code> loop is instantiated to loop through each <em>key:value</em> pair in the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary/" data-type="URL" data-id="https://blog.finxter.com/python-dictionary/" target="_blank">Dictionary</a> <code>students</code>.</p>
<p>If <code>v </code>(the value) is not in the <code>tally</code>, then the count for is set to 0. </p>
<p>Otherwise, if t<code>v</code> (the value) is in tally, the count is increased by 1.</p>
<p>Once the iteration is complete, the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-max/" data-type="URL" data-id="https://blog.finxter.com/python-max/" target="_blank"><code>max()</code></a> function is called to get the most common value in <code>tally</code> and output to the terminal.</p>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td>99</td>
</tr>
</tbody>
</table>
</figure>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube"><a href="https://blog.finxter.com/how-to-find-the-most-common-element-in-a-dictionary/"><img src="https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FcAK34XhOkI8%2Fhqdefault.jpg" alt="YouTube Video"></a><figcaption></figcaption></figure>
<hr class="wp-block-separator has-alpha-channel-opacity"/>
<h2>Method 4: Use max()</h2>
<p class="has-global-color-8-background-color has-background">This example uses <a rel="noreferrer noopener" href="https://blog.finxter.com/python-max/" data-type="URL" data-id="https://blog.finxter.com/python-max/" target="_blank"><code>max()</code></a> to retrieve the most common value in a Python dictionary. Simple, clean, efficient.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="1" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">common_val = max(list(students.values()), key=list(students.values()).count)</pre>
<p>The code above calls the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-max/" data-type="URL" data-id="https://blog.finxter.com/python-max/" target="_blank"><code>max()</code></a> function and passes two (2) arguments, the values of the<em> key:value</em> pairs of <code>students</code> and a <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" data-type="URL" data-id="https://blog.finxter.com/python-lists/" target="_blank">List</a> </code>object.</p>
<p>If output to the terminal, these two (2) arguments contain the following.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">print(list(students.values()))
print(list(students.values()).count)</pre>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td><code>[99, 76, 98, 99, 77, 98, 67, 61, 54, 76, 67, 99, 98, 49, 76, 99, 67, 54, 98, 100]<br />&lt;built-in method count of list object at 0x00000239566D3540></code></td>
</tr>
</tbody>
</table>
</figure>
<p>To retrieve the most common element, run the following 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="">print(common_val)</pre>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td>99</td>
</tr>
</tbody>
</table>
</figure>
<hr class="wp-block-separator has-alpha-channel-opacity"/>
<h2>Summary</h2>
<p>This article has provided four (4) ways to find the most common element in a Python Dictionary. These examples should give you enough information to select the best fitting for your coding requirements.</p>
<p>Good Luck &amp; Happy Coding!</p>
<hr class="wp-block-separator has-alpha-channel-opacity"/>
<h2>Programmer Humor – Blockchain</h2>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" width="280" height="394" src="https://blog.finxter.com/wp-content/uploads/2022/07/image-31.png" alt="" class="wp-image-457795" srcset="https://blog.finxter.com/wp-content/uploads/2022/07/image-31.png 280w, https://blog.finxter.com/wp-content/uplo...13x300.png 213w" sizes="(max-width: 280px) 100vw, 280px" /><figcaption><em>“Blockchains are like grappling hooks, in that it’s extremely cool when you encounter a problem for which they’re the right solution, but it happens way too rarely in real life.”</em> <strong>source </strong> – <a href="https://imgs.xkcd.com/comics/blockchain.png" data-type="URL" data-id="https://imgs.xkcd.com/comics/blockchain.png" target="_blank" rel="noreferrer noopener">xkcd</a></figcaption></figure>
</div>
</div>


https://www.sickgaming.net/blog/2022/09/...ictionary/
Reply



Forum Jump:


Users browsing this thread:
2 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016