What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

Check if Key exists in Dictionary (or Value) with Python code

  • Feb 18, 2023
  • 6 Minute Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Kusum Jain
Check if Key exists in Dictionary (or Value) with Python code

When dealing with large amounts of data using python dictionaries, it can be difficult to determine whether a specific key or value exists in it or not. We will learn in this article how to check if the key exists in a dictionary and also if the value exists in a dictionary, with code in Python.

What is a Dictionary?

A dictionary in python is a data structure that allows you to store data in key-value pairs. It is an essential thing to learn for every programmer because they will use it extensively for a number of use cases. Every element in a dictionary has a key and a value. The syntax would look something like this:

student_dictionary = {1: "Rahul", 2: "Abhijeet", 3: "Roma", 4: "Arpita"}

 

And the keys do not necessarily have to be integers and the values do not necessarily have to be strings. Dictionaries support strings, integers, tuples, lists, and even dictionaries as values. Keys can be strings, integers, and tuples. 

dictionary key and values

Now that we are familiar with the syntax and basic properties, let’s look at the actual problem that we want to solve here. 

Check if a key exists in the dictionary

First, we will learn about different methods to check if a key is available in the python dictionary. 

The ‘in’ operator

The simplest way to check is by using the 'in' operator. The ‘in’ operator can be used as a condition in an if statement to find out if the key is in the dictionary or not. It is a boolean operator that returns True if the key is present in the dictionary and False otherwise.

Here’s an example to understand how to use it.

student_dictionary = {1: "Rahul", 2: "Abhijeet", 3: "Roma", 4: "Arpita"}

if 1 in student_dictionary:
    print("Yes, 1 is in the student dictionary")
else:
    print("No, 1 is not in the student dictionary")

 

Output:

"Yes, 1 is in the student dictionary"

 

This is the most straightforward way, but there are other approaches to finding out the same.

The get() method

The get() method is a method offered by the dictionary class in python which takes an input of a key and returns its value. It will return a default value (which is None by default) if the key is not present.

Here is an example of this:

student_dictionary = {1: "Rahul", 2: "Abhijeet", 3: "Roma", 4: "Arpita"}

value_found = student_dictionary.get(1)
print(value_found)

 

This should output “Rahul”.

So how can we make use of this function to check if a key exists in a dictionary? Simple. If a key does not exist in the dictionary, the get() function will return a None value. Writing a conditional if statement to check if the value returned is none or not will do the job. Here’s the code:

student_dictionary = {1: "Rahul", 2: "Abhijeet", 3: "Roma", 4: "Arpita"}
value_found = student_dictionary.get(1)

if value_found != None:
    print("Yes, 1 is in the student dictionary")
else:
    print("No, 1 is not in the student dictionary")

 

Output:

"Yes, 1 is in the student dictionary"

 

Let's now do the search for another part of the pair.

Check if a value exists in a dictionary

The best way to check if a value exists in a python dictionary is the values() method. The values() method is available in the dictionary class of python that returns all the values of a dictionary in the form of a list inside a dict_values object.

Let us look at the code:

student_dictionary = {1: "Rahul", 2: "Abhijeet", 3: "Roma", 4: "Arpita"}

student_values = student_dictionary.values()
print(student_values)

 

Output:

dict_values(["Rahul", "Abhijeet", "Roma", "Arpita"])

 

The next step in finding if the value exists or not is writing a conditional statement with the ‘in’ operator to check if a value is in the dictionary. Let’s look at the code for finding out if the value “Rahul” exists in the student dictionary.

student_dictionary = {1: "Rahul", 2: "Abhijeet", 3: "Roma", 4: "Arpita"}
student_values = student_dictionary.values()

if "Rahul" in student_values:
    print("Yes, the value 'Rahul' exists in the student dictionary")
else:
    print("No, the value 'Rahul' does not exist in the student dictionary")

 

Output:

Yes, the value 'Rahul' exists in the student dictionary

 

Also, learn how to sort a python dictionary by a key or a value.

Conclusion

When working on a Python program, checking if a key is in a dictionary is very important. If your code is trying to access a key that does not exist, it will lead to a KeyError in Python breaking the program. The same goes for checking values. Although that will not cause an error, checking if a value is in a dictionary is essential if you want to validate the data. 

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Kusum Jain
I am an avid coder on CodeChef, I partake in hackathons regularly. I am an independent and self-motivated student with a love for coding and experiencing new things.