[Tut] How to Increment a Dictionary 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 Increment a Dictionary Value (/thread-99731.html) |
[Tut] How to Increment a Dictionary Value - xSicKxBot - 07-23-2022 How to Increment a Dictionary Value <div> <div class="kk-star-ratings kksr-auto kksr-align-left kksr-valign-top" data-payload="{"align":"left","id":"477275","slug":"default","valign":"top","reference":"auto","class":"","count":"1","readonly":"","score":"5","best":"5","gap":"5","greet":"Rate this post","legend":"5\/5 - (1 vote)","size":"24","width":"142.5","_legend":"{score}\/{best} - ({count} {votes})","font_factor":"1.25"}"> <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">In this article, you’ll learn how to <strong>increment a dictionary value in Python</strong>.</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 class="wp-embed-aspect-16-9 wp-has-aspect-ratio"><em>Trinity Bank keeps track of its latest mortgage rates in a Dictionary format. Recently there has been a steady increase in rates. How would Trinity Bank increment/increase the Dictionary value of a selected rate?</em></p> <figure class="wp-block-table is-style-stripes"> <table> <tbody> <tr> <td><code>mtg_rates = {'30-Year-Fixed': 5.625,<br /> '20-Year-Fixed': 5.250,<br /><code> </code>'10-Year-Variable': 5.125,<br /><code> </code>'7-Year-Variable': 5.011,<br /><code> </code>'5-Year-Variable': 4.625}</code></td> </tr> </tbody> </table> </figure> <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 increment a Dictionary value in Python?</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 Dictionary Key Name</li> <li><strong>Method 2</strong>: Use <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dict-get-method/" data-type="URL" data-id="https://blog.finxter.com/python-dict-get-method/" target="_blank"><code>Dictionary.get()</code></a></li> <li><strong>Method 3</strong>: Use <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary-update-method/" data-type="URL" data-id="https://blog.finxter.com/python-dictionary-update-method/" target="_blank"><code>Dictionary.update()</code></a></li> <li><strong>Method 4</strong>: Use <a rel="noreferrer noopener" href="https://blog.finxter.com/python-unpacking/" data-type="URL" data-id="https://blog.finxter.com/python-unpacking/" target="_blank"><code>Unpacking using the * Operator</code></a></li> <li><strong>Method 5</strong>: Use <a href="https://blog.finxter.com/python-dictionary-comprehension/" data-type="URL" data-id="https://blog.finxter.com/python-dictionary-comprehension/" target="_blank" rel="noreferrer noopener"><code>Dictionary Comprehension</code></a></li> </ul> <hr class="wp-block-separator has-alpha-channel-opacity"/> <h2>Method 1: Use Dictionary Key Name </h2> <p class="has-global-color-8-background-color has-background">This method passes an existing Dictionary Key Name to access and increment the appropriate Value.</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="">mtg_rates['30-Year-Fixed'] += 1 print(mtg_rates['30-Year-Fixed'])</pre> <p>In this example, the <strong>30-Year-Fixed</strong> mortgage rate is referenced by name <code>(mtg_rates['30-Year-Fixed'</code>]) and its value is incremented by one (1). </p> <p>Then, this updated value is saved back to <code>mtg_rates['30-Year-Fixed']</code> and output to the terminal.</p> <figure class="wp-block-table is-style-stripes"> <table> <tbody> <tr> <td><code>6.625</code></td> </tr> </tbody> </table> </figure> <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="Python Dictionary – The Ultimate Guide" width="780" height="439" src="https://www.youtube.com/embed/qX0qqEVpP5s?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> </div> </figure> <hr class="wp-block-separator has-alpha-channel-opacity"/> <h2>Method 2: Use Dictionary.get()</h2> <p class="has-global-color-8-background-color has-background">This method uses the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dict-get-method/" data-type="URL" data-id="https://blog.finxter.com/python-dict-get-method/" target="_blank"><code>Dictionary.get()</code></a> method and passes a Dictionary Key as an argument to retrieve and increment the corresponding Value.</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="">mtg_rates['20-Year-Fixed'] = mtg_rates.get('20-Year-Fixed') + 2 print(mtg_rates['20-Year-Fixed'])</pre> <p>In this example, the <strong>20 Year Fixed</strong> mortgage rate is referenced and accessed using <code>(mtg_rates.get('20-Year-Fixed')</code>). This value is then incremented by two (2).</p> <p>Then, this updated value is saved back to <code>mtg_rates['20-Year-Fixed']</code> and output to the terminal.</p> <figure class="wp-block-table is-style-stripes"> <table> <tbody> <tr> <td><code>7.25</code></td> </tr> </tbody> </table> </figure> <figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"> <div class="wp-block-embed__wrapper"> <iframe loading="lazy" title="Python dict.get() Method" width="780" height="585" src="https://www.youtube.com/embed/9LFw28twPFs?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> </div> </figure> <hr class="wp-block-separator has-alpha-channel-opacity"/> <h2>Method 3: Use Dictionary.update()</h2> <p class="has-global-color-8-background-color has-background">This method uses <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary-update-method/" data-type="URL" data-id="https://blog.finxter.com/python-dictionary-update-method/" target="_blank"><code>Dictionary.update()</code></a> to reference the appropriate Key and increment the Value.</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="">new_rate = mtg_rates['10-Year-Variable'] + 3 mtg_rates.update({'10-Year-Variable': new_rate}) print(mtg_rates['10-Year-Variable'])</pre> <p>In this example, the current value of a <strong>10 Year Variable</strong> mortgage rate is retrieved, incremented by three (3) and saved to <code>new_rate</code>.</p> <p>Next, the appropriate Key for the <em>key:value</em> pair is accessed, and the Value is updated to reflect the contents of <code>new_rate</code> and output to the terminal.</p> <figure class="wp-block-table is-style-stripes"> <table> <tbody> <tr> <td><code>8.125</code></td> </tr> </tbody> </table> </figure> <figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"> <div class="wp-block-embed__wrapper"> <iframe loading="lazy" title="Python Dictionary update() Method" width="780" height="585" src="https://www.youtube.com/embed/y7A8uLfGEfo?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> </div> </figure> <hr class="wp-block-separator has-alpha-channel-opacity"/> <h2>Method 4: Use Unpacking</h2> <p class="has-global-color-8-background-color has-background">This method uses <a rel="noreferrer noopener" href="https://blog.finxter.com/python-unpacking/" data-type="URL" data-id="https://blog.finxter.com/python-unpacking/" target="_blank"><code>Unpacking</code></a> to increment the Value of a key:value pair.</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="">mtg_rates = {**mtg_rates, '7-Year-Variable': 9.011} print(mtg_rates)</pre> <p>Above, accesses the <strong>7 Year Variable</strong> mortgage rate, increments the rate to the amount indicated (<code>9.011</code>), and outputs it to the terminal.</p> <figure class="wp-block-table is-style-stripes"> <table> <tbody> <tr> <td><code> 9.011</code></td> </tr> </tbody> </table> </figure> <hr class="wp-block-separator has-alpha-channel-opacity"/> <h2>Method 5: Use Dictionary Comprehension</h2> <p class="has-global-color-8-background-color has-background">This method increments all Mortgage Rates in one fell swoop using <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary-comprehension/" data-type="URL" data-id="https://blog.finxter.com/python-dictionary-comprehension/" target="_blank"><code>Dictionary Comprehension</code></a>.</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="1" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">new_rates = dict(((key, round(value*1.10, 3)) for key, value in mtg_rates.items())) print(new_rates)</pre> <p>Above, accesses each mortgage rate in the <code>mtg_rates</code> Dictionary and increments the rate by 1.10. Then, <a rel="noreferrer noopener" href="https://blog.finxter.com/python-round-a-simple-guide-with-video/" data-type="URL" data-id="https://blog.finxter.com/python-round-a-simple-guide-with-video/" target="_blank"><code>round()</code></a> is called to round the results down to three (3) decimal places. The result saves to <code>new_rates</code> and output to the terminal.</p> <figure class="wp-block-table is-style-stripes"> <table> <tbody> <tr> <td><code> {'30-Year-Fixed': 6.188, '20-Year-Fixed': 5.775, '10-Year-Variable': 5.638, '7-Year-Variable': 5.512, '5-Year-Variable': 5.088}</code></td> </tr> </tbody> </table> </figure> <hr class="wp-block-separator has-alpha-channel-opacity"/> <h2 class="wp-embed-aspect-16-9 wp-has-aspect-ratio">Summary</h2> <p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">These methods of incrementing a Dictionary Value should give you enough information to select the best one for your coding requirements.</p> <p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">Good Luck & Happy Coding!</p> <hr class="wp-block-separator has-alpha-channel-opacity"/> <h2>Regex Humor</h2> <div class="wp-block-image"> <figure class="aligncenter size-full is-resized"><img loading="lazy" src="https://blog.finxter.com/wp-content/uploads/2022/06/image-133.png" alt="" class="wp-image-428862" width="700" height="629" srcset="https://blog.finxter.com/wp-content/uploads/2022/06/image-133.png 785w, https://blog.finxter.com/wp-content/uploads/2022/06/image-133-300x270.png 300w, https://blog.finxter.com/wp-content/uploads/2022/06/image-133-768x691.png 768w" sizes="(max-width: 700px) 100vw, 700px" /><figcaption><em>Wait, forgot to escape a space. Wheeeeee[taptaptap]eeeeee.</em> (<a href="https://imgs.xkcd.com/comics/regular_expressions.png" data-type="URL" data-id="https://imgs.xkcd.com/comics/regular_expressions.png" target="_blank" rel="noreferrer noopener">source</a>)</figcaption></figure> </div> </div> https://www.sickgaming.net/blog/2022/07/19/how-to-increment-a-dictionary-value/ |