Sick Gaming
[Tut] How to Sort Words Alphabetically in Python? - 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 Words Alphabetically in Python? (/thread-99792.html)



[Tut] How to Sort Words Alphabetically in Python? - xSicKxBot - 08-11-2022

How to Sort Words Alphabetically in Python?

<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;541325&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&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-4-3 wp-has-aspect-ratio">Problem Formulation and Solution Overview</h2>
<p class="wp-embed-aspect-4-3 wp-has-aspect-ratio">In this article, you’ll learn how to sort words alphabetically in Python.</p>
<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">To make it more fun, we have the following running scenario:</p>
<p><em>Some English sayings, also known as <a rel="noreferrer noopener" href="https://www.engvid.com/english-resource/50-tongue-twisters-improve-pronunciation/" data-type="URL" data-id="https://www.engvid.com/english-resource/50-tongue-twisters-improve-pronunciation/" target="_blank">Tongue-Twisters</a>, are fun to try and say quickly. They are also used to improve non-English speaking individuals and small children’s fluency and pronunciation of the English language.</em></p>
<p><em>Imagine how challenging tongue twisters would be if sorted in alphabetical order!</em></p>
<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 sort a string in alphabetical order?</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 1</strong>: Use <a rel="noreferrer noopener" href="https://blog.finxter.com/python-string-methods/" data-type="URL" data-id="https://blog.finxter.com/python-string-methods/" target="_blank"><code>split()</code></a> and <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-sort-a-set-of-values/" data-type="URL" data-id="https://blog.finxter.com/how-to-sort-a-set-of-values/" target="_blank"><code>sort()</code></a></li>
<li><strong>Method 2</strong>: Use <a rel="noreferrer noopener" href="https://blog.finxter.com/python-string-methods/" data-type="URL" data-id="https://blog.finxter.com/python-string-methods/" target="_blank"><code>split()</code></a>, <a rel="noreferrer noopener" href="https://blog.finxter.com/python-sorted-function/" data-type="URL" data-id="https://blog.finxter.com/python-sorted-function/" target="_blank"><code>sorted()</code></a> and <a rel="noreferrer noopener" href="https://blog.finxter.com/python-string-join/" data-type="URL" data-id="https://blog.finxter.com/python-string-join/" target="_blank"><code>join()</code></a></li>
<li><strong>Method 3</strong>: Use <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"><code>Bubble Sort Algorithm</code></a></li>
<li><strong>Method 4</strong>: Use <a href="https://blog.finxter.com/pandas-dataframe-sort_values-method/" data-type="URL" data-id="https://blog.finxter.com/pandas-dataframe-sort_values-method/" target="_blank" rel="noreferrer noopener"><code>sort_values()</code></a></li>
</ul>
<hr class="wp-block-separator has-alpha-channel-opacity"/>
<h2>Method 1: Use split() and sort()</h2>
<p class="has-global-color-8-background-color has-background">This method uses Python’s built-in <a rel="noreferrer noopener" href="https://blog.finxter.com/python-string-methods/" data-type="URL" data-id="https://blog.finxter.com/python-string-methods/" target="_blank"><code>string</code></a> library to reference <a rel="noreferrer noopener" href="https://blog.finxter.com/python-string-methods/" data-type="URL" data-id="https://blog.finxter.com/python-string-methods/" target="_blank"><code>split()</code></a> and <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-sort-a-set-of-values/" data-type="URL" data-id="https://blog.finxter.com/how-to-sort-a-set-of-values/" target="_blank"><code>sort()</code></a> to display the words in <strong>ascending </strong>alphabetical order.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="1-2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">twister = 'how much wood would a woodchuck chuck if a woodchuck could chuck wood?'.lower().split()
twister.sort()
print(twister)</pre>
<p>Above declares a tongue twister, converts the entire string to lowercase (<code>lower()</code>) and breaks it apart (<code>split()</code>) by default, on the space (<code>' '</code>) character. The results save to <code>twister </code>in 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"><code>List</code></a> format. If output to the terminal, the following displays.</p>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td><code>['How', 'much', 'wood', 'would', 'a', 'woodchuck', 'chuck', 'if', 'a', 'woodchuck', 'could', 'chuck', 'wood?']</code></td>
</tr>
</tbody>
</table>
</figure>
<p>The following line sorts twister (<a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-sort-a-set-of-values/" data-type="URL" data-id="https://blog.finxter.com/how-to-sort-a-set-of-values/" target="_blank"><code>sort()</code></a>) in <strong>ascending</strong> alphabetical order. If output to the terminal, the following would display.</p>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td><code>['a', 'a', 'chuck', 'chuck', 'could', 'how', 'if', 'much', 'wood', 'wood?', 'woodchuck', 'woodchuck', 'would']</code></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-sort-words-alphabetically-in-python/"><img src="https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2F-UkcLQxzPA4%2Fhqdefault.jpg" alt="YouTube Video"></a><figcaption></figcaption></figure>
<hr class="wp-block-separator has-alpha-channel-opacity"/>
<h2>Method 2: Use split(), sorted() and join()</h2>
<p class="has-global-color-8-background-color has-background">This method uses Python’s built-in <a rel="noreferrer noopener" href="https://blog.finxter.com/python-string-methods/" data-type="URL" data-id="https://blog.finxter.com/python-string-methods/" target="_blank"><code>string</code></a> library to reference <a rel="noreferrer noopener" href="https://blog.finxter.com/python-string-methods/" data-type="URL" data-id="https://blog.finxter.com/python-string-methods/" target="_blank"><code>split()</code></a> and <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-sorted-function/" data-type="URL" data-id="https://blog.finxter.com/python-sorted-function/" target="_blank">sorted()</a></code> to display the words in <strong>descending</strong> alphabetical order.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="1-2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">twister = 'I scream, you scream, we all scream for ice cream!'.lower()
twister = ' '.join(sorted(twister.split(), reverse=True)) print(twister)</pre>
<p>Above declares a tongue twister, then converts the string to lowercase (<code>lower()</code>). The results save to <code>twister</code> in 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"><code>List</code></a> format. If output to the terminal, the following would display.</p>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td><code>['i', 'scream,', 'you', 'scream,', 'we', 'all', 'scream', 'for', 'ice', 'cream!']</code></td>
</tr>
</tbody>
</table>
</figure>
<p>The following line breaks it apart (<code>split()</code>) by default, on the space (<code>' '</code>) character. Then, <code>twister</code> is sorted (<code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-sorted-function/" data-type="URL" data-id="https://blog.finxter.com/python-sorted-function/" target="_blank">sorted()</a></code>) in <strong>descending</strong> alphabetical order (<code>reverse=True</code>). </p>
<p>The words are combined using the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-string-join/" data-type="URL" data-id="https://blog.finxter.com/python-string-join/" target="_blank"><code>join()</code></a> function, saved to <code>twister</code> and output to the terminal.</p>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td><code>['you', 'we', 'scream,', 'scream,', 'scream', 'ice', 'i', 'for', 'cream!', 'all']</code></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-sort-words-alphabetically-in-python/"><img src="https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FaGfYP9WhUsc%2Fhqdefault.jpg" alt="YouTube Video"></a><figcaption></figcaption></figure>
<hr class="wp-block-separator has-alpha-channel-opacity"/>
<h2>Method 3: Use Bubble Sort Algorithm</h2>
<p class="has-global-color-8-background-color has-background">This method uses the famous <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"><code></code></a><code><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"><code>Bubble Sort Algorithm</code></a></code>. This function accepts a <a href="https://blog.finxter.com/python-lists/" data-type="URL" data-id="https://blog.finxter.com/python-lists/" target="_blank" rel="noreferrer noopener"><code>List</code></a> and loops through each element, comparing two (2) values, the current element value and the next element value. The greater element floats to the top, and the loop continues until the <a href="https://blog.finxter.com/python-lists/">List </a>is sorted.</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="">twister = 'Which wristwatches are Swiss wristwatches?'.lower().split() def bubblesort(lst): for passesLeft in range(len(lst)-1, 0, -1): for i in range(passesLeft): if lst[i] > lst[i + 1]: lst[i], lst[i + 1] = lst[i + 1], lst[i] return ' '.join(lst) print(bubblesort(twister)) </pre>
<p>Above declares a tongue twister, converts the entire string to lowercase (<code>lower()</code>) and breaks it apart (<code>split()</code>) by default, on the space (<code>' '</code>) character. The results save to <code>twister </code>in 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"><code>List</code></a> format. If output to the terminal, the following displays.</p>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td><code>['which', 'wristwatches', 'are', 'swiss', 'wristwatches?']</code></td>
</tr>
</tbody>
</table>
</figure>
<p>Next, the <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"><code>bubblesort()</code></a> function is declared and accepts one (1) argument, an iterable <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" data-type="URL" data-id="https://blog.finxter.com/python-lists/" target="_blank"><code>List</code></a>. An explanation of this code is outlined above. </p>
<p>However, we modified the code slightly to return a new string containing the sorted <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" data-type="URL" data-id="https://blog.finxter.com/python-lists/" target="_blank"><code>List</code></a> values.</p>
<p>The <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"><code>bubblesort()</code></a> function is then called and passed <code>twister</code> as an argument. The results are output to the terminal.</p>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td><code> are swiss which wristwatches wristwatches?</code></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-sort-words-alphabetically-in-python/"><img src="https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FlyZQPjUT5B4%2Fhqdefault.jpg" alt="YouTube Video"></a><figcaption></figcaption></figure>
<hr class="wp-block-separator has-alpha-channel-opacity"/>
<h2>Method 4: Use sort_values()</h2>
<p class="has-global-color-8-background-color has-background">This function imports the <a href="https://blog.finxter.com/category/pandas-library/" data-type="URL" data-id="https://blog.finxter.com/category/pandas-library/" target="_blank" rel="noreferrer noopener">Pandas </a>Library to reference the <a rel="noreferrer noopener" href="https://blog.finxter.com/pandas-dataframe-sort_values-method/" data-type="URL" data-id="https://blog.finxter.com/pandas-dataframe-sort_values-method/" target="_blank"><code>sort_values()</code></a> function. This function sorts column(s) in a DataFrame.</p>
<p>To run this code error-free, install the required library. Click <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-install-pandas-in-python/" data-type="URL" data-id="https://blog.finxter.com/how-to-install-pandas-in-python/" target="_blank">here</a> for installation instructions. </p>
<p>To follow along, click <a rel="noreferrer noopener" href="https://blog.finxter.com/wp-content/uploads/2022/01/finxter.csv" data-type="URL" data-id="https://blog.finxter.com/wp-content/uploads/2022/01/finxter.csv" target="_blank">here</a> to download the <code>finxters.csv</code> file. Move this file to the current working directory.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="4" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import pandas as pd df = pd.read_csv('finxters.csv', skip_blank_lines=True, usecols=['FID', 'Username', 'Rank'])
rank_sort = df.sort_values(by=["Rank"], ascending=True)
print(rank_sort)</pre>
<p>Above, imports the <a rel="noreferrer noopener" href="https://blog.finxter.com/category/pandas-library/" data-type="URL" data-id="https://blog.finxter.com/category/pandas-library/" target="_blank">Pandas </a> library.</p>
<p>Then, the <code>finxter.csv</code> file is read in, omitting blank lines, selecting the three (3) stated columns and saving to <code>df</code>.</p>
<p>Next, sort is applied to the <code>Rank</code> column, which contains the words pertaining to a user’s achievement level. The DataFrame (<code>df</code>) is sorted based on this column and the results save to <code>rank_sort</code> and output to the terminal.</p>
<p>Below a snippet of the results displays.</p>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td></td>
<td>FID</td>
<td>Username</td>
<td>Rank</td>
</tr>
<tr>
<td>0</td>
<td>30022145 </td>
<td>wildone92</td>
<td>Authority</td>
</tr>
<tr>
<td>45</td>
<td>3002481</td>
<td>Moon_Star2</td>
<td>Authority</td>
</tr>
<tr>
<td>9</td>
<td>30022450</td>
<td>Gar_man </td>
<td>Authority</td>
</tr>
<tr>
<td>4</td>
<td>30022359</td>
<td>AliceM</td>
<td>Authority</td>
</tr>
<tr>
<td>24</td>
<td>3002328</td>
<td>Wall_2021</td>
<td>Authority</td>
</tr>
<tr>
<td>49</td>
<td>3002573</td>
<td>jJonesing</td>
<td>Authority</td>
</tr>
<tr>
<td>47</td>
<td>3002521</td>
<td>KerrStreet</td>
<td>Autodidact</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-sort-words-alphabetically-in-python/"><img src="https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2F-JKVy_HliQE%2Fhqdefault.jpg" alt="YouTube Video"></a><figcaption></figcaption></figure>
<hr class="wp-block-separator has-alpha-channel-opacity"/>
<h2 id="block-323ff1c3-82fc-4193-9c8d-125f5d3c2efb">Summary</h2>
<p id="block-ebf714b3-b2f5-494e-bcd5-0cd3b3709ed7">These four (4) methods of sorting words alphabetically should give you enough information to select the best one for your coding requirements.</p>
<p id="block-7790db1b-2ed9-424b-885a-382987e3d867">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/uploads/2022/07/image-31-213x300.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></p>
</div>


https://www.sickgaming.net/blog/2022/08/07/how-to-sort-words-alphabetically-in-python/