Interview Kickstart has enabled over 21000 engineers to uplevel.
A dictionary is a built-in container in Python that stores key-value pairs, with keys used as indexes. Here, keys can be numbers or strings, but they can’t be mutable sequences or objects like lists.
When dealing with a dictionary, we often need to get the value associated with a given key, but sometimes, the key might just not be there. When we index a dictionary (or dict) with a non-existent key, Python will throw an error. Therefore, it is a safe practice to check whether a given key already exists in the dictionary or not before trying to get its corresponding value. In this article, we’ll look at some different ways to do that.
If you are preparing for a tech interview, check out our technical interview checklist, interview questions page, and salary negotiation e-book to get interview-ready! Also, read Python String join() Method, Sum Function in Python, and How to Read and Write Files in Python for more specific insights and guidance on Python concepts and coding interview preparation.
Having trained over 9,000 software engineers, we know what it takes to crack the toughest tech interviews. Since 2014, Interview Kickstart alums have been landing lucrative offers from FAANG and Tier-1 tech companies, with an average salary hike of 49%. The highest ever offer received by an IK alum is a whopping $933,000!
At IK, you get the unique opportunity to learn from expert instructors who are hiring managers and tech leads at Google, Facebook, Apple, and other top Silicon Valley tech companies.
Want to nail your next tech interview? Sign up for our FREE Webinar.
In this article, we’ll discuss:
Some of the ways you can check if a given key already exists in a dictionary in Python are using:
Let us look at these methods in more detail and see how they’d work.
The has_key() method is a built-in method in Python that returns true if the dict contains the given key, and returns false if it isn’t. This method, however, has been removed from Python 3, so when we look at examples for has_key(), we’ll run the code in earlier versions of Python.
dictToCheck.has_key(keyToFind)
dictExample = {'Apples': 10,'Bananas': 20,'Chocolate': 30}
keyToFind = 'Apples'
if dictExample.has_key(keyToFind):
print "The given key exists in the dictionary"
else:
print "The given key does not exist in the dictionary."
keyToFind2 = 'Orange'
if dictExample.has_key(keyToFind2):
print "The given key exists in the dictionary"
else:
print "The given key does not exist in the dictionary."
The given key exists in the dictionary.
The given key does not exist in the dictionary.
We can also use the if-in statement to check if the key is in the dictionary.
if keyToFind in dictExample:
# Code to run if the key exists in the dictionary
else:
# Code to run if they key does not exist in the dictionary
dictExample = {'Apples': 10,'Bananas': 20,'Chocolate': 30}
keyToFind = 'Apples'
if keyToFind in dictExample:
print("The given key exists in the dictionary")
else:
print("The given key does not exist in the dictionary")
keyToFind2 = 'Orange'
if keyToFind2 in dictExample:
print("The given key exists in the dictionary")
else:
print("The given key does not exist in the dictionary")
The given key exists in the dictionary
The given key does not exist in the dictionary
The get() method takes a key as an argument along with an optional argument that states what value to return if the key is not found. By default, this optional argument returnValueIfNotFound is “None.” So, if we use get() on a key and get() returns None, then the key doesn’t exist in the dictionary.
dictToCheck.get(keyToFind, returnValueIfNotFound)
# Or, with default value of returnValueIfNotFound being ‘None’
dictToCheck.get(keyToFind)
dictExample = {'Apples': 10,'Bananas': 20,'Chocolate': 30}
keyToFind = 'Apples'
if dictExample.get(keyToFind) == None:
print("The given key does not exist in the dictionary")
else:
print("The given key exists in the dictionary")
keyToFind2 = 'Orange'
if dictExample.get(keyToFind2) == None:
print("The given key does not exist in the dictionary")
else:
print("The given key exists in the dictionary")
The given key exists in the dictionary
The given key does not exist in the dictionary
Another way to achieve this would be using the keys() function, which returns all the keys in a dictionary as a sequence. We will also make use of the in operator in this method.
dictToCheck.keys()
dictExample = {'Apples': 10,'Bananas': 20,'Chocolate': 30}
keyToFind = 'Apples'
if keyToFind in dictExample.keys():
print("The given key does not exist in the dictionary")
else:
print("The given key exists in the dictionary")
keyToFind2 = 'Orange'
if keyToFind2 in dictExample.keys():
print("The given key does not exist in the dictionary")
else:
print("The given key exists in the dictionary")
The given key does not exist in the dictionary
The given key exists in the dictionary
Yet another way to check if a key exists in a dict is through using try and except to handle the KeyError exception. When the key you’re trying to access is not in the dictionary, KeyError exception is raised.
Note that while exceptions usually fire faster than other methods, recovering from them is extremely slow. Hence, if possible, consider other fast approaches over this one wherever possible. It is still a simple and really fast way to accomplish the task.
We can simply handle the KeyError exception using try and except in the following way:
dictExample = {'Apples': 10,'Bananas': 20,'Chocolate': 30}
keyToFind = 'Apples'
try:
dictExample[keyToFind]
print('The given key exists in the dictionary')
except KeyError as error:
print('The given key does not exist in the dictionary')
keyToFind2 = 'Orange'
try:
dictExample[keyToFind2]
print('The given key exists in the dictionary')
except KeyError as error:
print('The given key does not exist in the dictionary')
The given key exists in the dictionary
The given key does not exist in the dictionary
Try-except is the fastest way to check if a key exists, but its use is not recommended over other comparably fast methods since recovery from try-except is much slower.
Using the if-in statement is also one of the fastest methods for checking if a key exists in a dictionary. In essence, try-except and if-in statements are significantly quicker than other methods. But between the two, the if-in statement or using the in operator is usually recommended for the purpose.
1. How do you check if a key exists or not in a dictionary?
You can check if a key exists or not in a dictionary using if-in statement/in operator, get(), keys(), handling 'KeyError' exception, and in versions older than Python 3, using has_key().
2. What will happen if I try to use has_key() in newer versions of Python, including and since Python 3?
If you try to use has_key() in newer versions of Python, including Python 3, you will get an Attribute error since has_key() is not available Python 3 onwards. The runtime error message will read: AttributeError: 'dict' object has no attribute 'has_key'
3. Which keyword can be used to check if a given key exists in a dictionary?
The keyword ‘in’ can be used to check if a given key exists in a dictionary or not. We can do this with the help of an if-in statement.
4. What is required in a valid dictionary key?
A dictionary key must be of a type that is immutable. So, types like integer, string, float, and boolean are acceptable, but types like lists or other dictionaries are not acceptable as keys.
5. What does the get() function return when the key does not exist?
If a value argument was provided stating what to return if a key does not exist, it returns that value; otherwise, it returns None.
Whether you’re a Coding Engineer gunning for Software Developer or Software Engineer roles, a Tech Lead, or you’re targeting management positions at top companies, Interview Kickstart offers courses specifically designed for your needs to help you with your technical interview preparation.
If you’re looking for guidance and help with getting started, sign up for our FREE webinar. As pioneers in the field of technical interview preparation, we have trained thousands of software engineers to crack the toughest coding interviews and land jobs at their dream companies, such as Google, Facebook, Apple, Netflix, Amazon, and more!
Attend our webinar on
"How to nail your next tech interview" and learn