python

Check if a value exists in a dictionary Python

A dictionary is a data structure in Python that is used to store data in key-value pairs. In order to check if a value exists in a dictionary, you can use the values() function and the 'in' keyword.

Check if a value exists in a dictionary Python

In order to check if a value exists in a dictionary:

  1. First, Get all the values from a dictionary using dict.values().
  2. Use "in" keyword to check if a value exists in the values of the dictionary using "value" in "values"

Solution 1: Using values() and "in" keyword

The dict.values() function is used to get all the values from a dictionary. It returns the values from the dictionary as a list. For example, if you have a dictionary {"1": "a", "2": "b"} and you use values() function then it will return dict_values(["a", "b"]). You can convert it to a list using list() function.

The "in" keyword is used to check if an item exists in a list or a key exists in a dictionary. We will combine these two to check if a value exists in a dictionary or not.

Code example

# create a dictionary
my_dict = {
    "name": "John",
    "city": "New York",
    "profession": "Engineer"
}

# get all values list
all_values = my_dict.values()

# check if a value - Engineer exists in the values list
if "Engineer" in all_values:
    print("Value exists in the dictionary")
else:
    print("Value does not exist in the dictionary")

Output

Value exists in the dictionary

The above code is creating a dictionary with three key-value pairs. It is then getting a list of all the values in the dictionary using the .values() method.

Finally, it is checking if the value "Engineer" is in the list of values using the 'in' keyword. If it is, it prints out "Value exists in the dictionary". Otherwise, it prints out "Value does not exist in the dictionary".


Solution 2: Check if value exist in dictionary using for loop

We can also use Python for loop to check whether a value exists in a dictionary or not. In order to do that We will iterate over the dictionary items and in each iteration, we will compare the value. If the value is found the loop is exited using the break keyword.

# create a dictionary
my_dict = {
    "name": "John",
    "city": "New York",
    "profession": "Engineer"
}

# use for loop to check if value - Engineer exists in the dictionary
for key in my_dict:
    if (my_dict[key] == 'Engineer'):
        print('Value exists in the dictionary')
        break;
else:
    print('Value does not exist in the dictionary')

Output

Value exists in the dictionary

This is an example of a for loop that checks if a given value exists in a dictionary. The code will print "Value exists in the dictionary" if the value is found, and "Value does not exist in the dictionary" if it is not.


Was this helpful?