Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How To Update A Key In A Dictionary In Python If The Key Doesn’t Exist?

#1
How To Update A Key In A Dictionary In Python If The Key Doesn’t Exist?

<div><p class="has-pale-cyan-blue-background-color has-background"><strong>Summary: </strong>To update a key in a dictionary if it doesn’t exist, you can check if it is present in the dictionary using the <code><strong>in</strong> </code>keyword along with the if statement and then update the key-value pair using subscript notation or <code><strong>update()</strong></code> method or the <strong>*</strong> operator. Another workaround for this is, using the <code><strong>s</strong></code><code><strong>etdefault(<em>key</em>[, <em>default</em>])</strong></code> method which updates the dictionary with the key-value pair only if it doesn’t exist in the dictionary otherwise, it returns the pre-existing items. </p>
<p><strong>Problem:</strong> Given a dictionary; how to update a key in it if the key does not exist?</p>
<p><strong>Example:</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="">device = { "brand": "Apple", "model": "iPhone 11",
} &lt; Some Method to Check if key-value pairs "color" : "red" and "year" : 2019 exists or not and then update/insert it in the dictionary &gt; print(device)</pre>
<p><strong>Output:</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="">{'brand': 'Apple', 'model': 'iPhone 11', 'color': 'red', 'year': 2019}</pre>
<p>To solve our problem statement, let us follow a modular approach and break down our discussion in this article into three parts. </p>
<ol>
<li>In the first section let us discuss the methods to update or insert a key, </li>
<li>In the second section, we shall be discussing the methods to check if the key is present in the dictionary,</li>
<li>Finally, we shall merge our concepts to reach the final solution. </li>
</ol>
<p>Without further delay let us dive into the solutions right away.</p>
<h2>Section 1: Insert/Update A Key In A <a href="https://blog.finxter.com/category/python-dictionary/" target="_blank" rel="noreferrer noopener">Dictionary</a></h2>
<h3><strong>Method 1: Create A New Key-Value Pair Assign It To Dictionary | Subscript Notation</strong></h3>
<p>We can create a new index key and then assign a value to it and then assign the key-value pair to the dictionary. Let us have a look at the following program which explains the syntax to create a new key-value pair and assign it to the dictionary: </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="">device = { "brand": "Apple", "model": "iPhone 11",
} device["year"] = 2019
print(device)</pre>
<p><strong>Output:</strong></p>
<p>{‘brand’: ‘Apple’, ‘year’: 2019, ‘model’: ‘iPhone 11’}</p>
<h3><strong>Method 2: Use The <em><span class="has-inline-color has-vivid-red-color">update()</span></em> Function</strong></h3>
<p>The <code>update()</code> method is used to insert or update a specific key-value pair in a dictionary. The item to be inserted can also be another iterable. Also, if the specified key is already present in the dictionary then the previous value will be overwritten. </p>
<p>The following code demonstrates the usage of the <code>update() </code>method:</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="">device = { "brand": "Apple", "model": "iPhone 11",
} device.update({"year" : 2019})
print(device)</pre>
<p><strong>Output:</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="">{'brand': 'Apple', 'model': 'iPhone 11', 'year': 2019}</pre>
<h3><strong>Method 3: Using The <em><span class="has-inline-color has-vivid-red-color"><a href="https://blog.finxter.com/what-is-asterisk-in-python/" target="_blank" rel="noreferrer noopener">*</a></span></em> Operator</strong></h3>
<p>We can combine an existing dictionary and a key-value pair using the * operator. Let us have a look at the following code to understand the concept and usage of the * operator to insert items in a dictionary.</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="">device = { "brand": "Apple", "model": "iPhone 11",
}
device = {**device,**{"year":2019}}
print(device)</pre>
<p><strong>Output:</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="">{'brand': 'Apple', 'model': 'iPhone 11', 'year': 2019}</pre>
<p><strong>Disclaimer: </strong>In the above methods if we do not check the presence of a key in the dictionary, then the value will be overwritten in the dictionary if the key and value are already existing in the dictionary. Now, that brings us to the second section of our discussion!</p>
<h2>Section 2: Check If A Key Is Present In A Dictionary</h2>
<h3><strong>Method 1: Using The <span class="has-inline-color has-vivid-red-color"><em>in</em></span> Keyword</strong></h3>
<p>The <code>in</code> keyword is used to check if a key is already present in the dictionary. The following program explains how we can use the <code>in</code> keyword.</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="">device = { "brand": "Apple", "model": "iPhone 11", "year":2018
} if "year" in device: print("key year is present!")
else: print("key year is not Present!") if "color" in device: print("key color is present!")
else: print("key color is not present!") </pre>
<p><strong>Output:</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="">key year is present!
key color is not present!</pre>
<p><img loading="lazy" width="512" height="512" class="wp-image-13309" style="width: 30px" src="https://blog.finxter.com/wp-content/uploads/2020/09/finxPythond.png" alt="snake unicode" srcset="https://blog.finxter.com/wp-content/uploads/2020/09/finxPythond.png 512w, https://blog.finxter.com/wp-content/uplo...00x300.png 300w, https://blog.finxter.com/wp-content/uplo...50x150.png 150w" sizes="(max-width: 512px) 100vw, 512px" /> <strong>Note: </strong>Just like the <code>in </code>keyword, we can use the<em><span class="has-inline-color has-vivid-red-color"> <code><strong>not in</strong></code></span></em> keyword to check if the key is not present in the dictionary. </p>
<h3><strong>Method 2: Using <em><span class="has-inline-color has-vivid-red-color">keys()</span></em> Function</strong></h3>
<p><code>keys()</code> is an inbuilt method that extracts the keys present in a dictionary and stores them in a list. Thus with the help of this inbuilt method, we can determine if a key is present in the dictionary. </p>
<p>Let us have a look a the following program to understand how to use the <code>keys()</code> method and check the availability of a key in the dictionary:</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="">device = { "brand": "Apple", "model": "iPhone 11", "year":2018
} if "year" in device.keys(): print("key year is present!")
else: print("key year is not Present!") if "color" in device.keys(): print("key color is present!")
else: print("key color is not present!") </pre>
<p><strong>Output:</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="">key year is present!
key color is not present!</pre>
<h3><strong>Method 3: Using <em><span class="has-inline-color has-vivid-red-color">has_key()</span></em> Function</strong></h3>
<p>If you are using <a href="https://blog.finxter.com/how-to-check-your-python-version/python-version/" target="_blank" rel="noreferrer noopener">Python 2.x</a> then you might fancy your chances with the has_key() method which is an inbuilt method in Python that returns true if the specified key is present in the dictionary else it returns false.</p>
<p><strong><span class="has-inline-color has-vivid-red-color">Caution:</span> </strong><code>has_key()</code> has been removed from Python 3 and also lags behind the <code>in</code> keyword while checking for the presence of keys in a dictionary in terms of performance. So you must use avoid using it if you are using <a href="https://blog.finxter.com/how-to-check-your-python-version/python-version/" target="_blank" rel="noreferrer noopener">Python 3 or above</a>.</p>
<p>Now let us have a look at the following program to understand how we can use the <code>has_key()</code> method:</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="">device = { "brand": "Apple", "model": "iPhone 11", "year":2018
} if device.has_key("year"): print("key year is present!")
else: print("key year is not Present!") if device.has_key("color"): print("key color is present!")
else: print("key color is not present!") </pre>
<p><strong>Output:</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="">key year is present!
key color is not present!</pre>
<p>Phew!!! Now, we are finally equipped with all the procedures to check as well as update a key in a dictionary if it does not exist in the dictionary. That brings us to the final stages of our discussion where we shall combine our knowledge from section 1 and section 2 to reach the desired output.</p>
<h2>Update Key In Dictionary If It Doesn’t Exist</h2>
<h3><strong>Solution 1: Using Concepts Discussed In Section 1 and Section 2</strong></h3>
<p>Since we are through with the concepts, let us dive into the program to implement them and get the final output:</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="">device = { "brand": "Apple", "model": "iPhone 11",
} # Method 1 : Create a New Key_Value pair and check using the in keyword
if "color" not in device: device["color"] = "red" # Method 2 : Use update() method and check using the not in keyword
if "year" not in device.keys(): device.update({"year" : 2019}) # Method 2 : Use * operator and check using the not in keyword
if "brand" not in device.keys(): device.update({"brand" : "Samsung" })
else: print(device)</pre>
<p><strong>Output:</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="">{'brand': 'Apple', 'model': 'iPhone 11', 'color': 'red', 'year': 2019}</pre>
<h3><strong>Solution 2: Using <em><span class="has-inline-color has-vivid-red-color">setdefault()</span></em> Method</strong></h3>
<p><code>setdefault()</code> is an inbuilt Python method which returns the value of a key if it already exists in the dictionary and if it does not exist then the key value pair gets inserted into the dictionary.</p>
<p>Let us have a look at the following program which explains the <code>setdefault()</code> method in python:</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="">device = { "brand": "Apple", "model": "iPhone 11", "color": "red"
} device.setdefault('year',2019)
print(device)</pre>
<p><strong>Output:</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="">{'brand': 'Apple', 'model': 'iPhone 11', 'color': 'red', 'year': 2019}</pre>
<h2>Conclusion</h2>
<p>I hope after reading this article you can check and update values in a dictionary with ease. In case you have any doubts regarding Python dictionaries, I highly recommend you to go through our <a href="https://blog.finxter.com/python-dictionary/" target="_blank" rel="noreferrer noopener">tutorial on Python dictionaries</a>. </p>
<p> Please <a href="https://blog.finxter.com/subscribe" target="_blank" rel="noreferrer noopener">subscribe </a>and <a href="http://blog.finxter.com/" target="_blank" rel="noreferrer noopener">stay tuned</a> for more interesting articles!</p>
<h2 class="wp-block-block">Where to Go From Here?</h2>
<p>Enough theory, let’s get some practice!</p>
<p>To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?</p>
<p><strong>Practice projects is how you sharpen your saw in coding!</strong></p>
<p>Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?</p>
<p>Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.</p>
<p>Join my free webinar <a rel="noreferrer noopener" href="https://blog.finxter.com/webinar-freelancer/" target="_blank">“How to Build Your High-Income Skill Python”</a> and watch how I grew my coding business online and how you can, too—from the comfort of your own home.</p>
<p><a href="https://blog.finxter.com/webinar-freelancer/" target="_blank" rel="noreferrer noopener">Join the free webinar now!</a></p>
<p>The post <a href="https://blog.finxter.com/how-to-update-a-key-in-a-dictionary-in-python-if-the-key-doesnt-exist/" target="_blank" rel="noopener noreferrer">How To Update A Key In A Dictionary In Python If The Key Doesn’t Exist?</a> first appeared on <a href="https://blog.finxter.com/" target="_blank" rel="noopener noreferrer">Finxter</a>.</p>
</div>


https://www.sickgaming.net/blog/2020/09/...snt-exist/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016