Python | Test if element is dictionary value
Last Updated :
17 Apr, 2023
Sometimes, while working with a Python dictionary, we have a specific use case in which we just need to find if a particular value is present in the dictionary as it's any key's value. This can have use cases in any field of programming one can think of. Let's discuss certain ways in which this problem can be solved using Python.
Check if a value exists in the dictionary using any() function
This is the method by which this problem can be solved. In this, we iterate through the whole dictionary using list comprehension and check for each key's values for a match using a conditional statement.
Python3
test_dict = {'gfg': 1, 'is': 2, 'best': 3}
# Check if key exist in dictionary using any()
if any([True for k,v in test_dict.items() if v == 21]):
print(f"Yes, It exists in dictionary")
else:
print(f"No, It doesn't exists in dictionary")
OutputNo, It doesn't exists in dictionary
Check if a value exists in the dictionary using a loop
This is the brute way in which this problem can be solved. In this, we iterate through the whole dictionary using loops and check for each key's values for a match using a conditional statement.
Python3
# initializing dictionary
test_dict = {'gfg' : 1, 'is' : 2, 'best' : 3}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Test if element is dictionary value
# Using loops
res = False
for key in test_dict:
if(test_dict[key] == 3):
res = True
break
# printing result
print("Is 3 present in dictionary : " + str(res))
Output :
The original dictionary is : {'best': 3, 'is': 2, 'gfg': 1}
Is 3 present in dictionary : True
Time complexity: O(N), where N is the number of key-value pairs in the dictionary.
Auxiliary space: O(1).
Check if a value exists in the dictionary using in operator and values()
This task can be performed by utilizing the above functionalities. The in operator can be used to get the true value of presence and the values function is required to extract all values of dictionaries.
Python3
# initializing dictionary
test_dict = {'gfg' : 1, 'is' : 2, 'best' : 3}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Test if element is dictionary value
# Using in operator and values()
res = 3 in test_dict.values()
# printing result
print("Is 3 present in dictionary : " + str(res))
Output :
The original dictionary is : {'best': 3, 'is': 2, 'gfg': 1}
Is 3 present in dictionary : True
Time Complexity: O(n), where n is the number of values in the dictionary test_dict.
Auxiliary Space: O(1), as no extra space is used.
Using the get() method of a dictionary
The get() method returns the value for a given key if it exists in the dictionary. If the key does not exist, it returns None. You can use this behavior to check if a value exists in the dictionary by checking if it is in the list returned by values().
Python3
test_dict = {'gfg': 1, 'is': 2, 'best': 3}
if 21 in test_dict.values():
print(f"Yes, It exists in dictionary")
else:
print(f"No, It doesn't exist in dictionary")
OutputNo, It doesn't exist in dictionary
Time complexity: O(n)
Auxiliary space: O(1)
Using isinstance() function:
Approach:
Check if the input value is of dictionary type or not.
If it is, check if the given element exists in any of the dictionary values.
If yes, return True. Else, return False.
Python3
def check_dict_value_1(d, val):
if isinstance(d, dict):
return any(val == v for v in d.values())
return False
my_dict = {'a': 1, 'b': 2, 'c': {'d': 3, 'e': 4}, 'f': 5}
my_value = 4
result = check_dict_value_1(my_dict, my_value)
print(result)
Time Complexity: O(n)
Auxiliary Space: O(1)
Similar Reads
Dictionary items in value range in Python In this article, we will explore different methods to extract dictionary items within a specific value range. The simplest approach involves using a loop.Using LoopThe idea is to iterate through dictionary using loop (for loop) and check each value against the given range and storing matching items
2 min read
Ways to change keys in dictionary - Python Given a dictionary, the task is to change the key based on the requirement. Let's see different methods we can do this task in Python. Example:Pythond = {'nikhil': 1, 'manjeet': 10, 'Amit': 15} val = d.pop('Amit') d['Suraj'] = val print(d)Output{'nikhil': 1, 'manjeet': 10, 'Suraj': 15} Explanation:T
2 min read
Python Program to Swap dictionary item's position Given a Dictionary, the task is to write a python program to swap positions of dictionary items. The code given below takes two indices and swap values at those indices. Input : test_dict = {'Gfg' : 4, 'is' : 1, 'best' : 8, 'for' : 10, 'geeks' : 9}, i, j = 1, 3 Output : {'Gfg': 4, 'for': 10, 'best':
4 min read
Merging or Concatenating two Dictionaries in Python Combining two dictionaries is a common task when working with Python, especially when we need to consolidate data from multiple sources or update existing records. For example, we may have one dictionary containing user information and another with additional details and we'd like to merge them into
2 min read
How to Compare Two Dictionaries in Python In this article, we will discuss how to compare two dictionaries in Python. The simplest way to compare two dictionaries for equality is by using the == operator.Using == operatorThis operator checks if both dictionaries have the same keys and values.Pythond1 = {'a': 1, 'b': 2} d2 = {'a': 1, 'b': 2}
2 min read
Python Dictionary Comprehension Like List Comprehension, Python allows dictionary comprehensions. We can create dictionaries using simple expressions. A dictionary comprehension takes the form {key: value for (key, value) in iterable}Python Dictionary Comprehension ExampleHere we have two lists named keys and value and we are iter
4 min read
How to Add Values to Dictionary in Python The task of adding values to a dictionary in Python involves inserting new key-value pairs or modifying existing ones. A dictionary stores data in key-value pairs, where each key must be unique. Adding values allows us to expand or update the dictionary's contents, enabling dynamic manipulation of d
3 min read
Add new keys to a dictionary in Python In this article, we will explore various methods to add new keys to a dictionary in Python. Let's explore them with examples:Using Assignment Operator (=)The simplest way to add a new key is by using assignment operator (=).Pythond = {"a": 1, "b": 2} d["c"] = 3 print(d)Output{'a': 1, 'b': 2, 'c': 3}
2 min read
Add Item after Given Key in Dictionary - Python The task of adding an item after a specific key in a Pythondictionary involves modifying the order of the dictionary's key-value pairs. Since Python dictionaries maintain the insertion order, we can achieve this by carefully placing the new key-value pair after the target key. For example, consider
4 min read
Python - Ways to remove a key from dictionary We are given a dictionary and our task is to remove a specific key from it. For example, if we have the dictionary d = {"a": 1, "b": 2, "c": 3}, then after removing the key "b", the output will be {'a': 1, 'c': 3}.Using pop()pop() method removes a specific key from the dictionary and returns its cor
3 min read