Python – Check if dictionary contains a specific value

Python – Check if dictionary contains a specific value

To check if a given dictionary contains a specified value in Python,

  1. Get the values from the dictionary using values() method. The method returns an iterator to the values in dictionary.
  2. Convert the iterator object to a list of values using list() built-in function.
  3. Now, check if the specified value is present in the dictionary using Python in membership operator.

Examples

1. Checking if dictionary contains value 20 in Python

We are given a Python dictionary in my_dict. We have to check if this dictionary contains the value 20.

As mentioned in the steps above, we shall get the values from the dictionary as a list using dict.values() method and list() function. Then we shall use the expression with membership operator as a condition in Python if else statement, and print whether the specified value is present in the dictionary or not.

Python Program

my_dict = {
    'apple': 10,
    'banana': 20,
    'cherry':30
}

value = 20

if value in list(my_dict.values()):
    print("The value is PRESENT in the dictionary.")
else:
    print("The value is NOT PRESENT in the dictionary.")
Run Code Copy

Output

The value is PRESENT in the dictionary.

Since the specified value is present in the dictionary, membership operator returned True, and if-block is executed.

Now, let us try to check if the value 40 is present in the dictionary. Change the value to 40, and run the program.

Python Program

my_dict = {
    'apple': 10,
    'banana': 20,
    'cherry':30
}

value = 40

if value in list(my_dict.values()):
    print("The value is PRESENT in the dictionary.")
else:
    print("The value is NOT PRESENT in the dictionary.")
Run Code Copy

Output

The value is NOT PRESENT in the dictionary.

Since the specified value is not present in the dictionary, membership operator returned False, and else-block is executed.

Summary

In this tutorial of Python Examples, we learned how to check if a dictionary contains specified value, with the help of well detailed examples.

Related Tutorials

Code copied to clipboard successfully 👍