Add Item if Key Does Not Exist in Python Dictionary

One of the ways to update Python dictionaries is to use dict_object[<key>]=<value>. In this way, the value of the issued key is updated (overwritten) if the key already exists; otherwise, a new key-value pair is created.

This article will discuss how we can add an item to the dictionary only when the key issued does not exist. Before that, here is an example where the existing value is overwritten if the key exists.

# Dictionary with two items
d0 = {
	"Bank": "KCB",
	"Branch": "Karen"
}
# d0 contains the "Bank" key and therefore is updated.
d0["Bank"] = "National Bank"
# d0 does not contain "rating"; therefore, it is added
d0["rating"] = 4.1
# updated dictionary, d0
print(d0)

Output

{'Bank': 'National Bank', 'Branch': 'Karen', 'rating': 4.1}

We will discuss three methods of adding an item to a Python dictionary if the issued key does not exist.

  • Method 1: Using the if conditional statement,
  • Method 2: Using <dict>.get() and if statement, and,
  • Method 3: Using <dict>.setdefault() function.

Method 1: Using conditional if statement

In this method, we use the if conditional statement to check if a key exists and, if not, create it.

d1 = {
	"Name": "Dell Latitude 7400",
	"Model": "Dell",
	"Price": 1400
}
# if the "description" key is not in d1, create it.
if not "description" in d1:
	d1["description"] = "This is a description of Dell Latitude 7400."
# Updated dictionary.
print(d1)
# "Name" already exists, so its value is not changed.
if not "Name" in d1:
	d1["Name"] = "HP Celeron"
print(d1)

Output:

{'Name': 'Dell Latitude 7400', 'Model': 'Dell', 'Price': 1400, 'description': 'This is a description of Dell Latitude 7400.'}
{'Name': 'Dell Latitude 7400', 'Model': 'Dell', 'Price': 1400, 'description': 'This is a description of Dell Latitude 7400.'}

A new item with “description” is added to d1 because it did not exist on the original d1. By default, the Python dictionary is iterable over the keys, but you can explicitly call d1.keys() and d1.values() to use iterables of keys and values, respectively.

Method 2: Using <dict>.get() and if conditional statement

The function <dict>.get(<key>, default=None) returns the value of the issued key if the key is in the dictionary; otherwise, the default value (None) is returned.

In this method, we need to check the return value of the get() function and insert an item into the dictionary if the issued key does not exist. Let’s see an example.

d2 = {
	"Brand": "Volvo",
	"Model": "S90",
}
# get() returns values if the key exists
print(d2.get("Model")) #S90
# "Model" already exists and therefore its value is not changed.
# d2.get("Model")==S90 and not None
if d2.get("Model") is None:
	d2["Model"] = "Ford"
print(d2)
# "Year" key is not in d2 therefore get() returns None
print(d2.get("Year")) # None
# if "Year" key is not in d2 create it.
if d2.get("Year") is None:
	d2["Year"] = 2019
# Updated dictionary. An item with the "Year" key is added
print(d2)

Output:

S90
{'Brand': 'Volvo', 'Model': 'S90'}
None
{'Brand': 'Volvo', 'Model': 'S90', 'Year': 2019}

As said before, get() returns None if the checked key does not exist by default. The code above leverages that fact. If get() returns None, create a new item.

Method 3: Using <dict>.setdefault() function.

This method works like get(), but unlike the get() function, <dict>.setdefault(<key>, default=None) inserts a new item to the dictionary if <key> does not exist.

“If <key> is in the dictionary, return its value. If not, insert <key> with a value of default and return default. default defaults to None”, Source: Documentation

d3 = {
	"Product": "Dell Latitude 7400",
	"Manufacturer": "Dell",
}
r1 = d3.setdefault("Product", "Dell Inspiron X78")
# print r2 - value returned by setdefault() function.
# It returns the issued value - Dell Inspiron X78
# If "Product" already exists (it does), do not update otherwise
# new item is created.
print(r1)
# Updated d3
print(d3)
r2 = d3.setdefault("Rating", 4.8)
# "Rating" key does not exist. Therefore, it is added
# to the dictionary d3 with the default value given (4.8)
print(r2)
# Updated d3
print(d3)

Output:

Dell Latitude 7400
{'Product': 'Dell Latitude 7400', 'Manufacturer': 'Dell'}
4.8
{'Product': 'Dell Latitude 7400', 'Manufacturer': 'Dell', 'Rating': 4.8}

The “Product” already exists in the original d3; therefore, its value is not overwritten, and setdefault() returns its value in the original dictionary. In the second case, “Rating” is not in the original d3, and therefore setdefault() function creates an item with the “Rating” key, and the default (4.8) is used as the value. In this case, the issued default value (4.8) is returned.

Conclusion

This article discussed three methods of updating the Python dictionary without overwriting existing values. First, we can use the if conditional statement to check if the key exists in the dictionary and if not, an item is created accordingly.

In the second method, we also check if the dictionary contains the key; if not, we create it. The last method uses the setdefault() function to create an item with the given key and default value if the issued key does not exist.