Python: Check if a value exists in the dictionary (3 Ways)

In this article we will discuss different ways to check if a value exists in a dictionary or not. We will cover the following ways,

  • Check if value exist in a dict using values() & if-in statement
  • Check if a value exists in python dictionary using for loop
  • Check if a value exists in a dictionary using any() and List comprehension

Suppose we have a dictionary of strings and ints i.e.

# Dictionary of string and int
word_freq = {
    "Hello": 56,
    "at": 23,
    "test": 43,
    "this": 78
}

Now in this dictionary we want to check if any key contains the value 43 or not. There are different ways to look for a value in a dictionary, let’s discuss them one by one,

Check if value exist in dict using values() & if-in statement

Python dictionary provides a method values(), which returns a sequence of all the values associated with keys in the dictionary. We can use ‘in’ keyword to check if our value exists in that sequence of values or not. For example,

Advertisements
value = 43

# python check if value exist in dict using "in" & values()
if value in word_freq.values():
    print(f"Yes, Value: '{value}' exists in dictionary")
else:
    print(f"No, Value: '{value}' does not exists in dictionary")

Output:

Yes, Value: '43' exists in dictionary

Here, value 43 exists our dictionary therefore it in statement evaluated to True.

Let’s look at a negative example, where we will try to check for a value that does not exist in the dictionary. For example,

value = 51

# python check if value exist in dict using "in" & values()
if value in word_freq.values():
    print(f"Yes, Value: '{value}' exists in dictionary")
else:
    print(f"No, Value: '{value}' does not exists in dictionary")

Output:

No, Value: '51' does not exists in dictionary

Here, value 51 does not exist in our dictionary therefore if statement evaluated to False.

Related Articles:

Check if a value exists in python dictionary using for loop

We can iterate over all the key-value pairs of dictionary using a for loop and while iteration we can check if our value matches any value in the key-value pairs. We have created a separate function for this. Let’s understand this with an example,

def check_value_exist(test_dict, value):
    do_exist = False
    for key, val in test_dict.items():
        if val == value:
            do_exist = True
    return do_exist

value = 43

# Iterate over all key, value pairs in dict and check if value exist
if check_value_exist(word_freq, value):
    print(f"Yes, Value: '{value}' exists in dictionary")
else:
    print(f"No, Value: '{value}' does not exists in dictionary")

Output:

Yes, Value: '43' exists in dictionary

As value 43 exists in our dictionary, therefore check_value_exist() returned True.

Check if a value exists in a dictionary using any() and List comprehension

Using list comprehension, iterate over a sequence of all the key-value pairs in the dictionary and create a bool list. The list will contain a True for each occurrence of our value in the dictionary. Then call any() function on the list of bools to check if it contains any True. If yes then it means that our value exists in any key-value pair of the dictionary.

# Check if key exist in dictionary using any()
if any([True for k,v in word_freq.items() if v == value]):
    print(f"Yes, Value: '{value}' exists in dictionary")
else:
    print(f"No, Value: '{value}' does not exists in dictionary")

Output:

Yes, Value: '43' exists in dictionary

Here, value 43 exists in the dictionary therefore any() returned True.

Conclusion:

So, these were the different ways to check if a value exists in a dictionary or not.

Pandas Tutorials -Learn Data Analysis with Python

   

Are you looking to make a career in Data Science with Python?

Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.

Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.

Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.

Join a LinkedIn Community of Python Developers

1 thought on “Python: Check if a value exists in the dictionary (3 Ways)”

  1. Thank you very much for this guide!
    I am currently learning Python using the book entitled “A Crash Course in Python”. Problem 6-6 asks to create a dictionary and look for empty values. After watching your video, I came up with what I think is a much more efficient way of doing this (compared to solutions posted on the web). Here is my code:
    favorite_languages = {
    ‘jen’ : ‘python’,
    ‘sarah’ : ‘c’,
    ‘jeremi’ : ‘COBOL’,
    ‘stephanie’ : ”,
    ‘patrick’ : ‘python’,
    ‘edward’ : ‘ruby’,
    ‘brandon’ : ”,
    ‘phil’ : ‘python’,
    ‘davis’ : ‘c sharp’,
    ‘ian’ : ‘ruby’,
    }
    for k, v in favorite_languages.items():
    if v != ”:
    print(k.title() + “, thank you for taking the poll.”)
    else:
    print(k.title() + “, please take the poll.”)

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top