0
0
PythonHow-ToBeginner · 3 min read

How to Check if Value Exists in Dictionary Python

To check if a value exists in a Python dictionary, use the in keyword with the dictionary's .values() method like value in my_dict.values(). This returns True if the value is found, otherwise False.
📐

Syntax

Use the in keyword with the dictionary's .values() method to check for a value.

  • value: The item you want to find.
  • my_dict: Your dictionary.
  • .values(): Returns all values in the dictionary.
  • in: Checks if the value is present.
python
value in my_dict.values()
💻

Example

This example shows how to check if a value exists in a dictionary and prints the result.

python
my_dict = {'apple': 1, 'banana': 2, 'cherry': 3}
value_to_check = 2

if value_to_check in my_dict.values():
    print(f"Value {value_to_check} exists in the dictionary.")
else:
    print(f"Value {value_to_check} does not exist in the dictionary.")
Output
Value 2 exists in the dictionary.
⚠️

Common Pitfalls

One common mistake is checking if a value exists by using in directly on the dictionary, which only checks keys, not values.

Wrong way:

value_to_check in my_dict

This checks keys, not values, so it will give incorrect results.

Right way:

value_to_check in my_dict.values()
python
my_dict = {'apple': 1, 'banana': 2}
value_to_check = 2

# Wrong: checks keys, not values
print(value_to_check in my_dict)  # Output: False

# Right: checks values
print(value_to_check in my_dict.values())  # Output: True
Output
False True
📊

Quick Reference

Summary tips for checking values in dictionaries:

  • Use value in my_dict.values() to check values.
  • Remember in my_dict checks keys only.
  • Use loops if you need to find keys for a specific value.

Key Takeaways

Use value in my_dict.values() to check if a value exists in a dictionary.
The in keyword alone checks keys, not values.
Checking values directly is simple and efficient for existence tests.
For finding keys by value, you need to loop through items.
Avoid confusing keys and values when searching in dictionaries.