Sick Gaming
[Tut] How to Sort a List of Tuples by Second Value - 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 Sort a List of Tuples by Second Value (/thread-99234.html)



[Tut] How to Sort a List of Tuples by Second Value - xSicKxBot - 04-18-2022

How to Sort a List of Tuples by Second Value

<div><p>In this article, you’ll learn how to <a href="https://blog.finxter.com/how-to-sort-a-list-of-tuples-most-pythonic-way/" data-type="post" data-id="10409" target="_blank" rel="noreferrer noopener">sort</a> a list of <a rel="noreferrer noopener" href="https://blog.finxter.com/category/python-tuple/" data-type="URL" data-id="https://blog.finxter.com/category/python-tuple/" target="_blank">tuples</a> by the second value in Python. </p>
<p>To make it more fun, we have the following running scenario:</p>
<p><em><strong>BridgeTech</strong> is a bridge restoration company. </em><em>They have asked you to sort and return the Top 10 elements from the Periodic Table based on the ‘Atomic Radius’ in descending order. </em> </p>
<blockquote class="wp-block-quote">
<p><em>The atomic radius of a chemical element is a measure of the size of its atom, usually the mean or typical distance from the center of the nucleus to the outermost isolated electron.</em></p>
<p><cite><a href="https://en.wikipedia.org/wiki/Atomic_radius#:~:text=The%20atomic%20radius%20of%20a,to%20the%20outermost%20isolated%20electron." data-type="URL" data-id="https://en.wikipedia.org/wiki/Atomic_radius#:~:text=The%20atomic%20radius%20of%20a,to%20the%20outermost%20isolated%20electron." target="_blank" rel="noreferrer noopener">Wikpedia</a></cite></p></blockquote>
<p><em>Click <a rel="noreferrer noopener" href="https://pubchem.ncbi.nlm.nih.gov/periodic-table/" data-type="URL" data-id="https://pubchem.ncbi.nlm.nih.gov/periodic-table/" target="_blank">here</a> to download the Periodic Table. Save this file as <code>periodic_table.csv</code> and move it to the current working directory.</em></p>
<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/13.1.0/72x72/1f4ac.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Question</strong>: How would you write the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-developer-income-and-opportunity/" data-type="post" data-id="189354" target="_blank">Python</a> code to accomplish this task?</p>
<p>We can accomplish this task by one of the following options:</p>
<ul>
<li><strong>Method 1</strong>: Use <a rel="noreferrer noopener" href="https://blog.finxter.com/numpy-tutorial/" data-type="post" data-id="1356" target="_blank"> </a><a rel="noreferrer noopener" href="https://blog.finxter.com/python-list-sort/" data-type="URL" data-id="https://blog.finxter.com/python-list-sort/" target="_blank"><code>sort()</code></a> and <a rel="noreferrer noopener" href="https://blog.finxter.com/a-simple-introduction-of-the-lambda-function-in-python/" data-type="URL" data-id="https://blog.finxter.com/a-simple-introduction-of-the-lambda-function-in-python/" target="_blank"><code>lambda</code></a></li>
<li><strong>Method 2</strong>: Use <a rel="noreferrer noopener" href="https://blog.finxter.com/python-list-sort/" data-type="URL" data-id="https://blog.finxter.com/python-list-sort/" target="_blank"><code>sort()</code></a> and <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-get-specific-elements-from-a-list/" data-type="URL" data-id="https://blog.finxter.com/how-to-get-specific-elements-from-a-list/" target="_blank"><code>itemgetter()</code></a></li>
<li><strong>Method 3</strong>: Use <code><a href="https://blog.finxter.com/python-sorted-function/" data-type="post" data-id="18072" target="_blank" rel="noreferrer noopener">sorted()</a></code> and <a rel="noreferrer noopener" href="https://blog.finxter.com/a-simple-introduction-of-the-lambda-function-in-python/" data-type="URL" data-id="https://blog.finxter.com/a-simple-introduction-of-the-lambda-function-in-python/" target="_blank"><code>lambda</code></a></li>
<li><strong>Method 4</strong>: Use a <a rel="noreferrer noopener" href="https://blog.finxter.com/daily-python-puzzle-bubble-sort/" data-type="URL" data-id="https://blog.finxter.com/daily-python-puzzle-bubble-sort/" target="_blank">Bubble Sort</a></li>
</ul>
<hr class="wp-block-separator" />
<h2>Preparation</h2>
<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">Before any data manipulation can occur, one (1) new library will require installation.</p>
<ul>
<li>The <a rel="noreferrer noopener" href="https://blog.finxter.com/pandas-quickstart/" data-type="URL" data-id="https://blog.finxter.com/pandas-quickstart/" target="_blank"><em>Pandas</em></a> library enables access to/from a <em>DataFrame</em>.</li>
</ul>
<p>To install this library, navigate to an <a rel="noreferrer noopener" href="https://blog.finxter.com/best-python-ide/" data-type="post" data-id="8106" target="_blank">IDE</a> terminal. At the command prompt (<code>$</code>), execute the code below. For the terminal used in this example, the command prompt is a dollar sign (<code>$</code>). Your terminal prompt may be different.</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="">$ pip install pandas</pre>
<p>Hit the <code>&lt;Enter&gt;</code> key on the keyboard to start the installation process.</p>
<p>If the installation was successful, a message displays in the terminal indicating the same.</p>
<hr class="wp-block-separator" />
<p>Feel free to view the PyCharm installation guide for the required library.</p>
<ul>
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-install-pandas-in-python/" target="_blank">How to install Pandas on PyCharm</a></li>
</ul>
<hr class="wp-block-separator" />
<p id="block-3b5c9c73-276c-4b84-a1bc-d5ba1de38d56">Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free.</p>
<pre class="EnlighterJSRAW wp-embed-aspect-16-9 wp-has-aspect-ratio" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import numpy as np
from operator import itemgetter</pre>
<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/13.1.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" />&nbsp;<strong>Note</strong>: The <code>operator</code> library is built-in to Python and does not require installation.</p>
<hr class="wp-block-separator" />
<h2>Method 1: Use Sort and a Lambda</h2>
<p class="has-global-color-8-background-color has-background">To sort a list of <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">tuples</a> based on the second element, use <a rel="noreferrer noopener" href="https://blog.finxter.com/python-list-sort/" data-type="URL" data-id="https://blog.finxter.com/python-list-sort/" target="_blank"><code>sort()</code></a> and <a rel="noreferrer noopener" href="https://blog.finxter.com/a-simple-introduction-of-the-lambda-function-in-python/" data-type="URL" data-id="https://blog.finxter.com/a-simple-introduction-of-the-lambda-function-in-python/" target="_blank"><code>lambda</code></a> in the <a href="https://pythononeliners.com/" data-type="URL" data-id="https://pythononeliners.com/" target="_blank" rel="noreferrer noopener">one-liner</a> expression <code>tups.sort(key=lambda x: x[1], reverse=True)</code>.</p>
<p>Here’s an example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="3" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">df = pd.read_csv('periodic_table.csv', usecols=['Name', 'AtomicRadius'])
tups = [tuple(x) for x in df.values.tolist()]
tups.sort(key=lambda x: x[1], reverse=True)
print(tups[0:10])</pre>
<p>The CSV file is read in preparation, and two (2) columns save to a DataFrame. The DataFrame then converts to a list of tuples (<code>tups</code>) using <a href="https://blog.finxter.com/list-comprehension/" data-type="URL" data-id="https://blog.finxter.com/list-comprehension/" target="_blank" rel="noreferrer noopener">List Comprehension</a>. </p>
<p>We are ready to sort!</p>
<p>A <a rel="noreferrer noopener" href="https://blog.finxter.com/a-simple-introduction-of-the-lambda-function-in-python/" data-type="URL" data-id="https://blog.finxter.com/a-simple-introduction-of-the-lambda-function-in-python/" target="_blank"></a><a rel="noreferrer noopener" href="https://blog.finxter.com/a-simple-introduction-of-the-lambda-function-in-python/" data-type="URL" data-id="https://blog.finxter.com/a-simple-introduction-of-the-lambda-function-in-python/" target="_blank"><code>lambda</code> </a>is passed as a parameter to <a rel="noreferrer noopener" href="https://blog.finxter.com/python-list-sort/" data-type="URL" data-id="https://blog.finxter.com/python-list-sort/" target="_blank"><code>sort()</code></a> indicating the sort element (<code>x[1]</code>), and the sort order is set to descending (<code>reverse=True</code>). The results save to <code>tups</code>.</p>
<p>To complete the process, <a rel="noreferrer noopener" href="https://blog.finxter.com/introduction-to-slicing-in-python/" data-type="URL" data-id="https://blog.finxter.com/introduction-to-slicing-in-python/" target="_blank">slicing</a> is performed, and the <em>Top 10</em> elements are sent to the terminal.</p>
<p><strong>Output</strong></p>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td><code>[('Francium', 348.0), ('Cesium', 343.0), ('Rubidium', 303.0), ('Radium', 283.0), ('Potassium', 275.0), ('Barium', 268.0), ('Actinium', 260.0), ('Strontium', 249.0), ('Curium', 245.0), ('Californium', 245.0)]</code></td>
</tr>
</tbody>
</table>
</figure>
<hr class="wp-block-separator" />
<h2>Method 2: Use Sort &amp; Itemgetter</h2>
<p class="has-global-color-8-background-color has-background">To sort a list of tuples by the second element, use the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-list-sort/" data-type="URL" data-id="https://blog.finxter.com/python-list-sort/" target="_blank"><code>sort()</code></a> and <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-get-specific-elements-from-a-list/" data-type="URL" data-id="https://blog.finxter.com/how-to-get-specific-elements-from-a-list/" target="_blank"><code>itemgetter()</code></a> functions in the expression <code>tuples.sort(key=itemgetter(1), reverse=True)</code>.</p>
<p>Here’s an example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="3" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">df = pd.read_csv('periodic_table.csv', usecols=['Name', 'AtomicRadius'])
tups = [tuple(x) for x in df.values.tolist()]
tups.sort(key=itemgetter(1), reverse=True)
print(tups[0:10])</pre>
<p>The CSV file is read in preparation, and two (2) columns save to a DataFrame. The DataFrame then converts to a List of Tuples (<code>tups</code>) using <a href="https://blog.finxter.com/list-comprehension/" data-type="URL" data-id="https://blog.finxter.com/list-comprehension/">List Comprehension</a>. </p>
<p>We are ready to sort!</p>
<p>The <a rel="noreferrer noopener" href="https://blog.finxter.com/python-list-sort/" data-type="URL" data-id="https://blog.finxter.com/python-list-sort/" target="_blank"><code>sort()</code></a> function passes a key (<code><a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-get-specific-elements-from-a-list/" data-type="URL" data-id="https://blog.finxter.com/how-to-get-specific-elements-from-a-list/" target="_blank">itemgetter</a>(n)</code>) where <code>n</code> is the sort element <code>(itemgetter(1)</code>), and the sort order is set to descending (<code>reverse=True</code>). </p>
<p>The results save to <code>tups</code>.</p>
<p>To complete the process, <a rel="noreferrer noopener" href="https://blog.finxter.com/introduction-to-slicing-in-python/" data-type="URL" data-id="https://blog.finxter.com/introduction-to-slicing-in-python/" target="_blank">slicing</a> is performed, and the <em>Top 10</em> elements are sent to the terminal.</p>
<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/13.1.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" />&nbsp;<strong>Note</strong>: The <code>itemgetter()</code> function is slightly faster than a <code>lambda</code>. Use <code>itemgetter</code> if speed and memory are a factor.</p>
<hr class="wp-block-separator" />
<h2>Method 3: Use Sorted &amp; Lambda</h2>
<p class="has-global-color-8-background-color has-background">To sort a list of tuples by the second element, combine the functions <a rel="noreferrer noopener" href="https://blog.finxter.com/python-list-sort/" data-type="URL" data-id="https://blog.finxter.com/python-list-sort/" target="_blank"><code>sorted()</code></a> and <a rel="noreferrer noopener" href="https://blog.finxter.com/a-simple-introduction-of-the-lambda-function-in-python/" data-type="URL" data-id="https://blog.finxter.com/a-simple-introduction-of-the-lambda-function-in-python/" target="_blank"><code>lambda</code></a> in the expression <code>sorted(tups, key=lambda xSadx[1]), reverse=True)</code> and assign the resulting sorted list to the original variable <code>tups</code>. </p>
<p>Here’s an example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="3" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">df = pd.read_csv('periodic_table.csv', usecols=['Name', 'AtomicRadius'])
tups = [tuple(x) for x in df.values.tolist()]
tups = sorted(tups, key=lambda xSadx[1]), reverse=True)
print(tups[0:10])</pre>
<p>The CSV file is read in preparation, and two (2) columns save to a DataFrame. The DataFrame then converts to a List of Tuples (<code>tups</code>) using <a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" data-type="URL" data-id="https://blog.finxter.com/list-comprehension/" target="_blank">List Comprehension</a>. </p>
<p>We are ready to sort!</p>
<p>A <code><a rel="noreferrer noopener" href="https://blog.finxter.com/a-simple-introduction-of-the-lambda-function-in-python/" data-type="URL" data-id="https://blog.finxter.com/a-simple-introduction-of-the-lambda-function-in-python/" target="_blank"></a><a rel="noreferrer noopener" href="https://blog.finxter.com/a-simple-introduction-of-the-lambda-function-in-python/" data-type="URL" data-id="https://blog.finxter.com/a-simple-introduction-of-the-lambda-function-in-python/" target="_blank">lambda</a></code><a rel="noreferrer noopener" href="https://blog.finxter.com/a-simple-introduction-of-the-lambda-function-in-python/" data-type="URL" data-id="https://blog.finxter.com/a-simple-introduction-of-the-lambda-function-in-python/" target="_blank"> </a>is passed as a parameter to <a rel="noreferrer noopener" href="https://blog.finxter.com/python-list-sort/" data-type="URL" data-id="https://blog.finxter.com/python-list-sort/" target="_blank"><code>sorted()</code></a>, indicating the sort element (<code>x[1]</code>), and the sort order is set to descending (<code>reverse=True</code>). The results save to <code>tups</code>.</p>
<p>To complete the process, <a rel="noreferrer noopener" href="https://blog.finxter.com/introduction-to-slicing-in-python/" data-type="URL" data-id="https://blog.finxter.com/introduction-to-slicing-in-python/" target="_blank">slicing</a> is performed, and the <em>Top 10</em> elements are sent to the terminal.</p>
<hr class="wp-block-separator" />
<h2>Method 4: Use Bubble Sort</h2>
<p class="has-global-color-8-background-color has-background">To sort a List of <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">Tuples</a> by the second element, you can also modify a sorting algorithm from scratch such as <a rel="noreferrer noopener" href="https://blog.finxter.com/daily-python-puzzle-bubble-sort/" data-type="URL" data-id="https://blog.finxter.com/daily-python-puzzle-bubble-sort/" target="_blank">Bubble Sort</a> to access the second (or n-th) tuple value as a basis for sorting.</p>
<p>Here’s an example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="4-13" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">df = pd.read_csv('periodic_table.csv', usecols=['Name', 'AtomicRadius'])
tups = [tuple(x) for x in df.values.tolist()] def sort_tuples_desc(tups, idx): length = len(tups) for i in range(0, length): for j in range(0, length-i-1): if (tups[j][idx] &lt; tups[j + 1][idx]): tmp = tups[j] tups[j] = tups[j+1] tups[j+1] = tmp return tups
print(sort_tuples_desc(tups, 1)[0:10])</pre>
<p>The CSV file is read in preparation, and two (2) columns save to a DataFrame. The DataFrame then converts to a List of Tuples (<code>tups</code>) using <a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" data-type="URL" data-id="https://blog.finxter.com/list-comprehension/" target="_blank">List Comprehension</a>. </p>
<p>We are ready to sort!</p>
<p>A sort function <code>sort_tuples_desc</code> is created and passed two (2) parameters: a List of Tuples (<code>tups</code>), and the sort element (<code>idx</code>). Then, the infamous Bubble Sort is performed on the elements.</p>
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Bubble-sort with Hungarian (&quot;Csángó&quotWink folk dance" width="780" height="439" src="https://www.youtube.com/embed/lyZQPjUT5B4?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</figure>
<p>This function returns a List of Tuples sorted in descending order.</p>
<p>To complete the process, <a rel="noreferrer noopener" href="https://blog.finxter.com/introduction-to-slicing-in-python/" data-type="URL" data-id="https://blog.finxter.com/introduction-to-slicing-in-python/" target="_blank">slicing</a> is performed, and the <em>Top 10</em> elements are sent to the terminal.</p>
<hr class="wp-block-separator" />
<h2>Summary</h2>
<p>These four (4) methods of sorting a List of Tuples based on the second element should give you enough information to select the best one for your coding requirements.</p>
<p>Good Luck &amp; Happy Coding!</p>
<hr class="wp-block-separator" />
</div>


https://www.sickgaming.net/blog/2022/04/12/how-to-sort-a-list-of-tuples-by-second-value/