How to check if a value exists in a Python dictionary?

Published on Aug. 22, 2023, 12:17 p.m.

To check if a value exists in a Python dictionary, you can use the in operator with the values() method, as shown below:

my_dict = {'key1': 10, 'key2': 45, 'key3': 23}
if 45 in my_dict.values():
    print("Value exists in dictionary")
else:
    print("Value does not exist in dictionary")

In this example, the in operator is used with my_dict.values() to check if the value 45 exists in the dictionary. If the value is found, the program will print “Value exists in dictionary”, otherwise it will print “Value does not exist in dictionary”.

Alternatively, you can also use a loop to iterate over the dictionary’s values and check if the value exists, as shown below:

my_dict = {'key1': 10, 'key2': 45, 'key3': 23}
value_exists = False
for value in my_dict.values():
    if value == 45:
        value_exists = True
if value_exists:
    print("Value exists in dictionary")
else:
    print("Value does not exist in dictionary")

In this example, a loop is used to iterate over the dictionary’s values and check if the value 45 exists. If the value is found, the program will set the value_exists variable to True. At the end of the loop, it checks the value of value_exists and prints the appropriate message.

Tags: