To update a key in a dictionary if it doesn’t exist, you can check if it is present in the dictionary using the in
keyword along with the if
statement, and then update the key-value pair using subscript notation or update()
method or the asterisk * operator.
This approach will be examined in Section 1 of this article.
The setdefault(key[, default])
method updates the dictionary with the key-value pair only if the key doesn’t exist. Otherwise, it returns the pre-existing items.
This approach will be examined in Section 2 of this article.
Let’s dive into the article, where we’ll explain all of this and more in an easy-to-follow, step-by-step manner. Go! 🚀
Problem Formulation and Overview
Problem: Given a dictionary. How to update a key in it if the key does not exist?
Example:
device = { "brand": "Apple", "model": "iPhone 11", } < Some Method to Check if key-value pairs "color":"red" and "year":2019 exists or not and then update/insert it in the dictionary > print(device)
Output:
{'brand': 'Apple', 'model': 'iPhone 11', 'color': 'red', 'year': 2019}
To solve our problem statement, let us follow a modular approach and break down our discussion in this article into three parts.
- In the first section, let us discuss the methods to update or insert a key,
- In the second section, we shall be discussing the methods to check if the key is present in the dictionary,
- Finally, we shall merge our concepts to reach the final solution.
Without further delay, let us dive into the solutions right away.
Section 1: Insert/Update Key in a Dictionary
Method 1: Create a New Key-Value Pair and Assign it to Dictionary | Subscript Notation
We can create a new index key, 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:
device = { "brand": "Apple", "model": "iPhone 11", } device["year"] = 2019 print(device)
Output:
{'brand': 'Apple', 'year': 2019, 'model': 'iPhone 11'}
Method 2: Use The update() Function
The update()
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, the previous value will be overwritten.
The following code demonstrates the usage of the update()
method:
device = { "brand": "Apple", "model": "iPhone 11", } device.update({"year" : 2019}) print(device)
Output:
{'brand': 'Apple', 'model': 'iPhone 11', 'year': 2019}
Method 3: Using the Asterisk * Operator
We can combine an existing dictionary and a key-value pair using the double-asterisk **
unpacking 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.
device = { "brand": "Apple", "model": "iPhone 11", } device = {**device, **{"year":2019}} print(device)
Output:
{'brand': 'Apple', 'model': 'iPhone 11', 'year': 2019}
🛑 Disclaimer: In the above methods, if we do not check the presence of a key in the dictionary, the value will be overwritten in the dictionary if the key and value already exist.
Now, that brings us to the second section of our discussion!
Section 2: Check if a Key is Present in a Dictionary
Method 1: Using in Keyword
The membership operator keyword in
is used to check if a key is already present in the dictionary.
The following program explains how we can use the in
keyword.
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!")
Output:
key year is present! key color is not present!
Note: Just like the in
keyword, we can use the not in
keyword to check if the key is not present in the dictionary.
Method 2: Using keys() Function
The built-in keys()
dictionary method extracts the keys present in a dictionary and stores them in an iterable. Thus with the help of this inbuilt method, we can determine if a key is present in the dictionary.
Let us have a look a the following program to understand how to use the keys()
method and check the availability of a key in the dictionary:
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!")
Output:
key year is present! key color is not present!
Method 3: Using has_key() Function
If you are using Python 2, 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
.
Caution: has_key()
has been removed from Python 3 and also lags behind the in
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 Python 3 or above.
Now let us have a look at the following program to understand how we can use the has_key()
method:
# Python 2 Only!! 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!")
Output:
key year is present! key color is not present!
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.
Update Key In Dictionary If It Doesn’t Exist
Solution 1: Using Concepts Discussed In Section 1 and Section 2
Since we are through with the concepts, let us dive into the program to implement them and get the final output:
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)
Output:
{'brand': 'Apple', 'model': 'iPhone 11', 'color': 'red', 'year': 2019}
Solution 2: Using setdefault() Method
The Python dictionary setdefault()
method returns the value of a key if it already exists in the dictionary. If it does not exist, the key-value pair gets inserted into the dictionary.
Let us have a look at the following program, which explains the setdefault()
method in Python:
device = { "brand": "Apple", "model": "iPhone 11", "color": "red" } device.setdefault('year',2019) print(device)
Output:
{'brand': 'Apple', 'model': 'iPhone 11', 'color': 'red', 'year': 2019}
Conclusion
After reading this article, I hope you can check and update values in a dictionary with ease.
In case you have any doubts regarding Python dictionaries, I highly recommend you go through our tutorial on Python dictionaries.
Please subscribe and stay tuned for more interesting articles!
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. 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?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming 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.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.