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

Summary: 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 * operator. Another workaround for this is, using the setdefault(key[, default]) method which updates the dictionary with the key-value pair only Theif doesn’t exist in the dictionary otherwise, it returns the pre-existing items.

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.

  1. In the first section let us discuss the methods to update or insert a key,
  2. In the second section, we shall be discussing the methods to check if the key is present in the dictionary,
  3. Finally, we shall merge our concepts to reach the final solution.

Without further delay let us dive into the solutions right away.

Table of Contents

Section 1: Insert/Update A Key In A Dictionary

Method 1: Create A New Key-Value Pair Assign It To Dictionary | Subscript Notation

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:

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 then 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 * Operator

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.

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, 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!

Section 2: Check If A Key Is Present In A Dictionary

Method 1: Using The in Keyword

The in keyword 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!

snake unicode

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

keys() 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.

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.x 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.

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:

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

setdefault() 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.

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

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 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!

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?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

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.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

Author: admin

Leave a Reply

Your email address will not be published.