The easiest way to check if a key exists in a Python dictionary is to use the in operator. This operator evaluates the membership of a value in a dictionary and will evaluate to True if the key exists, otherwise to False.
This tutorial will go through the in operator and other ways to check if a key exists in a dictionary with examples.
Table of contents
- Introduction
- Check if a Key Exists in a Dictionary Using the in Operator
- Check if a Key Exists in a Dictionary Using get()
- Check if a Key Exists in a Dictionary Using keys()
- Check If Key And Value Exists In Dictionary Using items()
- Check if Multiple Keys Exists in a Dictionary Using all()
- Handling the KeyError Exception
- Summary
Introduction
A Python dictionary is a built-in Python container that stores elements as a key-value pair. As of Python version 3.7, a dictionary is an ordered collection that is mutable and does not allow duplicates. For versions before 3.7, dictionaries are unordered. We can write dictionaries using curly brackets to contain the key-value pairs. Let’s look at an example of a dictionary to store the characteristics of the electron particle:
electron_dict = { "mass":0.51, "charge": -1, "spin": 1/2, } print(electron_dict)
{'mass': 0.51, 'charge': -1, 'spin': 0.5}
The left-hand side of the colon is the key, and the right-hand side is the value. A single key-value pair is a dictionary item, and we can refer to a dictionary item using the key name.
Check if a Key Exists in a Dictionary Using the in Operator
The easiest way to check if a key exists in a dictionary is to use an if... in
statement. The in operator invokes the method __contains__()
to check whether a key is in a dictionary or not. Let’s look at an example of using the in operator to check if a vegetable exists in a dictionary of vegetables.
veg_dict = {"spinach":15, "broccolli":10, "carrot":23, "kale":5, "leek":30} key = "lettuce" if key in veg_dict: print(f'Key: {key} found') else: print(f'Key: {key} not found')
In the above program, we define a key variable and assign “lettuce” to it. We use the if... in
statement to check if that key exists and print the found statement. Otherwise, we print the not found statement. Let’s run the code to see what happens:
Key: lettuce not found
The key “lettuce
” is not present in the dictionary, and therefore we get the not found message.
Check if a Key Exists in a Dictionary Using has_key()
In Python 2.x, we were able to use dict.has_key()
to check if a key exists in a dictionary, but this function does not exist in Python 3.x. Let’s look at an example of using the has_key()
for the Python 3.x version
veg_dict = {"spinach":15, "broccolli":10, "carrot":23, "kale":5, "leek": 30} key = "kale" if veg_dict.has_key(key): print(f'Key: {key} found') else: print(f'Key: {key} not found')
If you try to use has_key() instead of if… in to search for a key, you will return the following error:
AttributeError: 'dict' object has no attribute 'has_key'
For checking if a key exists in Python3, ensure you use the in operator instead.
Check if a Key Exists in a Dictionary Using get()
The get() method returns the value of the item with the specified key. The syntax for the get() method is:
dictionary.get(keyname, value)
The get()
method accepts a key and has an optional parameter, value to return if the key is not found. The default for value is None. Let’s use the get()
method to check if a vegetable exists in our vegetable dictionary:
veg_dict = {"spinach":15, "broccolli":10, "carrot":23, "kale":5, "leek":30} key = "lettuce" if veg_dict.get(key) == None: print(f'Key: {key} not found') else: print(f'Key: {key} found')
In the above program, we define a key variable and assign “lettuce” to it. We use get() to check if that key returns a value in the dictionary. Let’s run the code to see what happens:
Key: lettuce not found
The key “lettuce” is not present in the dictionary, and therefore we get the key not found message.
Check if a Key Exists in a Dictionary Using keys()
The dict.keys() method gives us all the keys present in a dictionary. We can use the keys() method with an if… in statement to check if a key belongs to a specified dictionary. Let’s look at an example with our vegetable dictionary:
veg_dict = {"spinach":15, "broccolli":10, "carrot":23, "kale":5, "leek":30} key = "broccolli" if key in veg_dict.keys(): print(f'Key: {key} found') else: print(f'Key: {key} not found')
We check to see if the key “broccoli” is in the veg_dict dictionary in the above code. Let’s run the code to see what happens.
Key: broccolli found
The key is present in the dictionary, and therefore we get the key found message.
Check If Key And Value Exists In Dictionary Using items()
We can check if a key-value pair exists in a dictionary using dict.items(). The items() function returns a list of the key-value tuples present in the dictionary. We can use the if… in statement to check if a given pair exists in a dictionary. Let’s look at an example with our vegetable dictionary.
veg_dict = {"spinach":15, "broccolli":10, "carrot":23, "kale":5, "leek":30} key_value = ("spinach",15) if key_value in veg_dict.items(): print(f'Key: {key_value} found') else: print(f'Key: {key_value} not found')
The above code defines a key-value tuple and checks whether it exists in the list of tuples returned by the items() function. Note that the search is case-sensitive, so define the key-value tuple you want to search for accounting for case sensitivity, or you can use upper() or lower() to make the search case-insensitive. Let’s run the code to see what happens:
Key: ('spinach', 15) found
The spinach key-value tuple exists in veg_dict.items().
Check if Multiple Keys Exists in a Dictionary Using all()
You can check if multiple keys exist in a dictionary using the all() function together with a list comprehension. Let’s look at an example with our vegetable dictionary:
veg_dict = {"spinach":15, "broccolli":10, "carrot":23, "kale":5, "leek":30} keys = ("spinach","leek") if all (key in veg_dict for key in keys): print(f'Both keys {keys} found') else: print(f' Not all of the keys: {keys} found')
The above code defines a tuple of keys to check in the dictionary. The in operator checks if each key exists in the dictionary and returns a list of True and False values depending on if the key is present. The all() function checks if the values are all True, which tells us that all keys are present in the dictionary. If not all the values are True, the all() function returns False. Let’s run the code to see what happens:
Both keys ('spinach', 'leek') found
Both the keys are present in the dictionary. Therefore the all() function evaluates to true, and we get the found print statement.
Handling the KeyError Exception
We can avoid our programs crashing due to a non-existent key by using a try-except clause to handle the KeyError exception. The KeyError exception occurs whenever our program does not find a specified key in a dictionary within the code. Let’s look at an example of the try-except clause with our vegetable dictionary:
veg_dict = {"spinach":15, "broccolli":10, "carrot":23, "kale":5, "leek":30} key = "asparagus" try: veg_dict[key] except KeyError as err: print('Key not found')
Let’s run the code to see what happens:
Key not found
The program successfully handles the KeyError.
Summary
Congratulations on reading to the end of this article! The most straightforward way to search for keys in a dictionary is to use the in operator. You can use get(), keys() with the in operator to search for keys. You can use items() with the in operator to search for key-value pairs. The all() function is helpful for checking if several keys are all present in a dictionary.
For further reading on dictionaries, go to the articles:
- How to Add to a Dictionary in Python
- How to Sort a Dictionary by Value in Python
- How to Iterate Over a Dictionary in Python
- How to Create a Nested Dictionary in Python
Go to the Python online courses page to learn more about coding in Python for data science and machine learning.
Have fun and happy researching!
Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.