Open In App

Check if Value Exists in Python Dictionary

Last Updated : 10 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We are given a dictionary and our task is to check whether a specific value exists in it or not. For example, if we have d = {'a': 1, 'b': 2, 'c': 3} and we want to check if the value 2 exists, the output should be True. Let's explore different ways to perform this check in Python.

Naive Approach

This approach directly checks if the value exists in the dictionary using the in operator with d.values().

Python
d = {'a': 10, 'b': 20, 'c': 30}
v = 20

if v in d.values():
    print(f"The value {v} exists in the dictionary.")
else:
    print(f"The value {v} does not exist in the dictionary.")

Output
The value 20 exists in the dictionary.

Explanation:

  • The in operator is used with d.values(), which returns a view of all values in the dictionary.
  • It checks if the given value v exists in the given dictionary.

Using a List Comprehension

This approach uses a list comprehension to create a list of dictionary values and then checks for the value's existence.

Python
d = {'a': 10, 'b': 20, 'c': 30}
v = 20

if v in [v for v in d.values()]:
    print(f"The value {v} exists in the dictionary.")
else:
    print(f"The value {v} does not exist in the dictionary.")

Output
The value 20 exists in the dictionary.

Explanation:

  • A list comprehension iterates over d.values() and creates a list of values.
  • The in operator checks if the value v exists in the list.

Using Exception Handling

This approach uses try and except to handle a ValueError when the value is not found.

Python
d = {'a': 10, 'b': 20, 'c': 30}
v = 20

try:
    if v in d.values():
        print(f"The value {v} exists in the dictionary.")
    else:
        raise ValueError
except ValueError:
    print(f"The value {v} does not exist in the dictionary.")

Output
The value 20 exists in the dictionary.

Explanation:

  • The try block checks if the value exists in the dictionary.
  • If the value is not found, it raises a ValueError and handles it with the except block.

Related Articles:


Next Article
Article Tags :
Practice Tags :

Similar Reads