Register for our webinar

How to Nail your next Technical Interview

1 hour
Loading...
1
Enter details
2
Select webinar slot
*Invalid Name
*Invalid Name
By sharing your contact details, you agree to our privacy policy.
Step 1
Step 2
Congratulations!
You have registered for our webinar
check-mark
Oops! Something went wrong while submitting the form.
1
Enter details
2
Select webinar slot
*All webinar slots are in the Asia/Kolkata timezone
Step 1
Step 2
check-mark
Confirmed
You are scheduled with Interview Kickstart.
Redirecting...
Oops! Something went wrong while submitting the form.
close-icon
Iks white logo

You may be missing out on a 66.5% salary hike*

Nick Camilleri

Head of Career Skills Development & Coaching
*Based on past data of successful IK students
Iks white logo
Help us know you better!

How many years of coding experience do you have?

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Iks white logo

FREE course on 'Sorting Algorithms' by Omkar Deshpande (Stanford PhD, Head of Curriculum, IK)

Thank you! Please check your inbox for the course details.
Oops! Something went wrong while submitting the form.
Our June 2021 cohorts are filling up quickly. Join our free webinar to Uplevel your career
close
closeAbout usWhy usInstructorsReviewsCostFAQContactBlogRegister for Webinar

Check Whether a Given Key Already Exists in a Dictionary in Python

Last updated by Dipen Dadhaniya on Sep 25, 2024 at 10:58 PM | Reading time: 9 minutes

The fast well prepared banner

Attend our Free Webinar on How to Nail Your Next Technical Interview

WEBINAR +LIVE Q&A

How To Nail Your Next Tech Interview

Check Whether a Given Key Already Exists in a Dictionary in Python
Hosted By
Ryan Valles
Founder, Interview Kickstart
strategy
Our tried & tested strategy for cracking interviews
prepare list
How FAANG hiring process works
hiring process
The 4 areas you must prepare for
hiring managers
How you can accelerate your learnings

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:

  • Ways to Check If a Given Key Already Exists in a Dictionary in Python
  • Check If Key Exists Using has_key()
  • Check If Key Exists Using if-in statement or in Operator
  • Check If Key Exists Using get()
  • Check if Key Exists Using keys()
  • Handling 'KeyError' Exception
  • Performance Comparison
  • FAQs on Finding if Key Exists in Dictionary

Ways to Check If a Given Key Already Exists in a Dictionary in Python

Some of the ways you can check if a given key already exists in a dictionary in Python are using:

  • has_key()
  • if-in statement/in Operator
  • get()
  • keys()
  • Handling 'KeyError' Exception

Let us look at these methods in more detail and see how they’d work.

Check If Key Exists Using has_key()

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.

Syntax

dictToCheck.has_key(keyToFind)

Example

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

Output

The given key exists in the dictionary.

The given key does not exist in the dictionary.

Check If Key Exists Using if-in Statement or in Operator

We can also use the if-in statement to check if the key is in the dictionary.

Syntax

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

Example

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")


Output

The given key exists in the dictionary

The given key does not exist in the dictionary

Check If Key Exists Using get()

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.

Syntax

dictToCheck.get(keyToFind, returnValueIfNotFound)

# Or, with default value of returnValueIfNotFound being ‘None’

dictToCheck.get(keyToFind)

Example

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")


Output

The given key exists in the dictionary

The given key does not exist in the dictionary

Check If Key Exists Using keys()

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.

Syntax

dictToCheck.keys()

Example

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")

Output

The given key does not exist in the dictionary

The given key exists in the dictionary

Handling 'KeyError' Exception

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:

Example

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')


Output

The given key exists in the dictionary

The given key does not exist in the dictionary

Performance Comparison

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.

FAQs on Finding If Key Exists in Dictionary

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.

Ready to Nail Your Next Coding Interview?

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!

Sign up now!

Last updated on: 
November 20, 2024
Author

Dipen Dadhaniya

Engineering Manager at Interview Kickstart

Attend our Free Webinar on How to Nail Your Next Technical Interview

Register for our webinar

How to Nail your next Technical Interview

1
Enter details
2
Select webinar slot
First Name Required*
Last Name Required*
By sharing your contact details, you agree to our privacy policy.
Step 1
Step 2
Congratulations!
You have registered for our webinar
check-mark
Oops! Something went wrong while submitting the form.
1
Enter details
2
Select webinar slot
Step 1
Step 2
check-mark
Confirmed
You are scheduled with Interview Kickstart.
Redirecting...
Oops! Something went wrong while submitting the form.

Check Whether a Given Key Already Exists in a Dictionary in Python

Worried About Failing Tech Interviews?

Attend our webinar on
"How to nail your next tech interview" and learn

Ryan-image
Hosted By
Ryan Valles
Founder, Interview Kickstart
blue tick
Our tried & tested strategy for cracking interviews
blue tick
How FAANG hiring process works
blue tick
The 4 areas you must prepare for
blue tick
How you can accelerate your learnings
Register for Webinar
entroll-image