Python Check if Key Exists in Dictionary

We will discuss how to check if a key already exists in a dictionary in Python. Dictionaries are an essential data structure in Python, allowing you to store and access data in a key-value pair format. It is often necessary to check whether a certain key already exists in a dictionary. You may need to check if the key exists before adding a new key-value pair or updating an existing one.

Quick Examples to Check Key Exists in Dictionary

We will discuss different ways of checking if a key in a python dictionary already exists. Following are quick real-world examples. These examples are what you need to know.


# Example 
preferences = {'color': 'blue', 'font_size': 'large'}
if 'color' in preferences:
  preferences['color'] = 'red'
print(preferences) 

# Example
cart = {'apple': 3, 'banana': 5}
if 'apple' in cart:
  cart['apple'] += 2
else:
  cart['apple'] = 2
print(cart) 

# Example
performance = {'dataset_1': 0.8, 'dataset_2': 0.9}
if 'dataset_1' in performance:
  performance['dataset_1'] = 0.85
print(performance)  

1. Python Check if Key Exists in Dictionary

The first and most used method in the list is get() method which can be used to check if a key exists in a dictionary. The get() method in Python’s dictionary data structure allows you to determine if a specific key is present in the dictionary. This can be useful in various situations where you want to update the value associated with a key in the dictionary only if the key exists.


employee_titles = {
"John": "Manager", 
"Jane": "Assistant Manager",
 "Bob": "Associate"
}

if employee_titles.get("John"):
    print("John is a member of our team.")
else:
    print("John is not a member of our team.")

1.1 Using get() function along with in keyword

To check if the key already exists in a python dictionary or not the get() function along with in keyword can be used. Below is an example where you can see how we find if a key exists in the dictionary or not.


d = {'key1': 'value1', 'key2': 'value2'}

if 'key1' in d and d.get('key1') is not None:
  print('Key exists in dictionary')
else:
  print('Key does not exist in dictionary')

2. Use items() Method to Check if Key Exists

To check if a specific key already exists in a dictionary, item() method can be used along with a for loop. By iterating over the key-value pairs in the dictionary and comparing the keys to the desired key, you can determine if the key is present in the dictionary.


customer_orders = {
    "Ali": ["shirt", "hat"],
    "NNK": ["pants", "shoes"],
    "Hanif": ["belt", "coat"],
}

found = False
for customer, order in customer_orders.items():
    if customer == "Ali":
        found = True
        break

if found:
    print(" Ali's order is in the dictionary.")
else:
    print("don't have an order from Ali ")

3. Use the keys() Method to Check if Key Exists in Python

In Python, the keys() method is a built-in method of the dict class that returns a new object of type dict_keys, which is a view of the keys in the dictionary. It can be used along with a for loop to check if a specific key already exists in a dictionary.


pet_quantities = {"unicorns": 3, "dragons": 1}

found = False
for pet in pet_quantities.keys():
    if pet == "unicorns":
        found = True
        break

if found:
    print("unicorns is in the petting zoo.")
else:
    print("unicorns isn't in the petting zoo.")

4. Use the setdefault() Method

The setdefault() method in Python’s built-in dictionary data type can be used to check if a key already exists in a dictionary. By setting a default value for the key using the setdefault() method, you can determine if the key is present in the dictionary by checking the returned value.


language_versions = {
    "Python": "3.9",
    "Java": "15",
    "C++": "20",
}
ruby_version = language_versions.setdefault("Ruby", "")
if ruby_version == "":
    print("Ruby not in the dictionary.")
else:
    print(" Ruby is in the dictionary.")

5. Use the pop() Method

This method can be used in conjunction with a try-except block to check if a key already exists in a dictionary. The pop() method in Python’s built-in dictionary data type allows you to remove a key-value pair from the dictionary and return the value associated with the key.


library_versions = {
    "NumPy": "1.20",
    "pandas": "1.1",
    "SciPy": "1.6",
}
try:
    sklearn_version = library_versions.pop("Scikit-learn")
    print("The 'Scikit-learn' key already exists ")
except KeyError:
    print("The 'Scikit-learn' key does not exist")

6. Use any() Method

You can use the any() function in combination with the in keyword to check if a key already exists in a dictionary. The any() function in Python is a built-in function that returns True if at least one element of an iterable is True, and False if all elements are False or the iterable is empty.


subject_offerings = {
    "Computer Science": "Yes",
    "Mathematics": "Yes",
    "Physics": "Yes",
}

if any("Astronomy" in subject_offerings):
    print("'Astronomy' key already exists ")
else:
    print("'Astronomy' key does not exist ")

7. The Fastest way to check if a key already exists in python dictionary

We have discussed different methods to check if a key is already in the python dictionary. But primarily only the in and get() functions are the recommend and most common way of doing the job. So we will consider the comparison between the two. On my machine, the result is below. It seems that the in keyword is much faster than the get() function.


from timeit import timeit

d = {'key1': 'value1', 'key2': 'value2'}
def test_in_operator():
  return 'key1' in d
def test_get_method():
  return d.get('key1') is not None

print(timeit(test_in_operator))
print(timeit(test_get_method))

# Output
# 0.13456200000655372
# 0.21518350001133513

Summary and Conclusion

In this article, we discussed several approaches to check if a key already exists in a dictionary in Python. We covered the built-in in operator, the get() method. We provided examples of how to use each of these approaches, and we discussed the pros and cons of each method. If you have any questions or need further assistance, please don’t hesitate to comment.

Leave a Reply