I am a bit late, but another way is to use list comprehension and the any
function, that takes an iterable and returns True
whenever one element is True
:
# Checking if string 'Mary' exists in the lists of the dictionary values
print any(any('Mary' in s for s in subList) for subList in myDict.values())
If you wanna count the number of element that have «Mary» in them, you can use sum()
:
# Number of sublists containing 'Mary'
print sum(any('Mary' in s for s in subList) for subList in myDict.values())
# Number of strings containing 'Mary'
print sum(sum('Mary' in s for s in subList) for subList in myDict.values())
From these methods, we can easily make functions to check which are the keys or values matching.
To get the keys containing ‘Mary’:
def matchingKeys(dictionary, searchString):
return [key for key,val in dictionary.items() if any(searchString in s for s in val)]
To get the sublists:
def matchingValues(dictionary, searchString):
return [val for val in dictionary.values() if any(searchString in s for s in val)]
To get the strings:
def matchingValues(dictionary, searchString):
return [s for s i for val in dictionary.values() if any(searchString in s for s in val)]
To get both:
def matchingElements(dictionary, searchString):
return {key:val for key,val in dictionary.items() if any(searchString in s for s in val)}
And if you want to get only the strings containing «Mary», you can do a double list comprehension :
def matchingStrings(dictionary, searchString):
return [s for val in dictionary.values() for s in val if searchString in s]
In this article we will discuss six different ways to check if key exists in a Dictionary in Python.
Table of Contents
Suppose we have a dictionary of string and int i.e.
# Dictionary of string and int word_freq = { "Hello": 56, "at": 23, "test": 43, "this": 78 }
Now we want to check if key ‘test’ exist in this dictionary or not.
There are different ways to do this. Let’s discuss them one by one.
Check if key in Python Dictionary using if-in statement
We can directly use the ‘in operator’ with the dictionary to check if a key exist in dictionary or nor. The expression,
Advertisements
key in dictionary
Will evaluate to a boolean value and if key exist in dictionary then it will evaluate to True, otherwise False. Let’s use this to check if key is in dictionary or not. For example,
# Dictionary of string and int word_freq = { "Hello": 56, "at": 23, "test": 43, "this": 78 } key = 'test' # python check if key in dict using "in" if key in word_freq: print(f"Yes, key: '{key}' exists in dictionary") else: print(f"No, key: '{key}' does not exists in dictionary")
Output:
Yes, key: 'test' exists in dictionary
Here it confirms that the key ‘test’ exist in the dictionary.
Now let’s test a negative example i.e. check if key ‘sample’ exist in the dictionary or not i.e.
# Dictionary of string and int word_freq = { "Hello": 56, "at": 23, "test": 43, "this": 78 } key = 'sample' # python check if key in dict using "in" if key in word_freq: print(f"Yes, key: '{key}' exists in dictionary") else: print(f"No, key: '{key}' does not exists in dictionary")
Output:
No, key: 'sample' does not exists in dictionary
Here it confirms that the key ‘sample’ does not exist in the dictionary.
Check if Dictionary has key using get() function
In python, the dict class provides a method get() that accepts a key and a default value i.e.
dict.get(key[, default])
Behavior of this function,
- If given key exists in the dictionary, then it returns the value associated with this key,
- If given key does not exists in dictionary, then it returns the passed default value argument.
- If given key does not exists in dictionary and Default value is also not provided, then it returns None.
Let’s use get() function to check if given key exists in dictionary or not,
# Dictionary of string and int word_freq = { "Hello": 56, "at": 23, "test": 43, "this": 78 } key = 'sample' # check if key exists in dictionary by checking if get() returned None if word_freq.get(key) is not None: print(f"Yes, key: '{key}' exists in dictionary") else: print(f"No, key: '{key}' does not exists in dictionary")
Output:
No, key: 'sample' does not exists in dictionary
Here it confirmed that the key ‘sample’ does not exist in the dictionary.
We passed ‘sample’ argument in the get() function, without any default value. As our dictionary does not contain ant key ‘sample’ and no default value is provided, therefore it returned None.
If we pass the default value along with the key and if key does not exist in the dictionary, then it returns the default value. For example,
key = 'sample' # check if key exists in dictionary by checking if get() returned default value if word_freq.get(key, -1) != -1: print(f"Yes, key: '{key}' exists in dictionary") else: print(f"No, key: '{key}' does not exists in dictionary")
Output:
No, key: 'sample' does not exists in dictionary
Here it confirmed that the key ‘sample’ does not exist in the dictionary.
We passed ‘sample’ argument in the get() function, along with the default value -1. As our dictionary does not contain ant key ‘sample’, so get() function returned the the default value.
We cannot always be sure with the result of dict.get(), that key exists in dictionary or not . Therefore, we should use dict.get() to check existence of key in dictionary only if we are sure that there cannot be an entry of key with given default value.
keys() function of the dictionary returns a sequence of all keys in the dictionary. So, we can use ‘in’ keyword with the returned sequence of keys to check if key exist in the dictionary or not. For example,
word_freq = { "Hello": 56, "at": 23, "test": 43, "this": 78 } key = 'test' if key in word_freq.keys(): print(f"Yes, key: '{key}' exists in dictionary") else: print(f"No, key: '{key}' does not exists in dictionary")
Output:
Yes, key: 'test' exists in dictionary
Here it confirms that the key ‘test’ exist in the dictionary.
Check if key in Python Dictionary using try/except
If we try to access the value of key that does not exist in the dictionary, then it will raise KeyError. This can also be a way to check if exist in dict or not i.e.
def check_key_exist(test_dict, key): try: value = test_dict[key] return True except KeyError: return False # Dictionary of string and int word_freq = { "Hello": 56, "at": 23, "test": 43, "this": 78 } key = 'test' # check if dictionary has key in python if check_key_exist(word_freq, key): print(f"Yes, key: '{key}' exists in dictionary") else: print(f"No, key: '{key}' does not exists in dictionary")
Output:
Yes, key: 'test' exists in dictionary
Here it confirms that the key ‘test’ exist in the dictionary.
In function check_key_exist(), it access the value of given key. If key does not exist then KeyError occurs, in that case it returns False, otherwise it returns True
Check if key not in Python Dictionary using ‘if not in’ statement
In all the above example, we checked if key exist in dictionary or not. But if want to check if key doesn’t exist in dictionary then we can directly use ‘not in’ with dictionary i.e.
word_freq = { "Hello": 56, "at": 23, "test": 43, "this": 78 } key = 'sample' # Check if key not in dict python if key not in word_freq: print(f"No, key: '{key}' does not exists in dictionary") else: print(f"Yes, key: '{key}' exists in dictionary")
Output:
No, key: 'sample' does not exists in dictionary
Here it confirms that the key ‘test’ exist in the dictionary.
Check if key exist in Python Dictionary using has_key()
dict provides a function has_key() to check if key exist in dictionary or not. But this function is discontinued in python 3. So, below example will run in python 2.7 only i.e.
if word_freq.has_key('test'): print("Yes 'test' key exists in dict") else: print("No 'test' key does not exists in dict")
Output:
Yes, key: 'test' exists in dictionary
Here it confirms that the key ‘test’ exist in the dictionary.
The complete example is as follows.
def check_key_exist(test_dict, key): try: value = test_dict[key] return True except KeyError: return False def main(): # Dictionary of string and int word_freq = { "Hello": 56, "at": 23, "test": 43, "this": 78 } print("*** Python: check if key in dictionary using if-in statement***") key = 'test' # python check if key in dict using "in" if key in word_freq: print(f"Yes, key: '{key}' exists in dictionary") else: print(f"No, key: '{key}' does not exists in dictionary") key = 'sample' # python check if key in dict using "in" if key in word_freq: print(f"Yes, key: '{key}' exists in dictionary") else: print(f"No, key: '{key}' does not exists in dictionary") print("*** Python: check if dict has key using get() function ***") key = 'sample' # check if key exists in dictionary by checking if get() returned None if word_freq.get(key) is not None: print(f"Yes, key: '{key}' exists in dictionary") else: print(f"No, key: '{key}' does not exists in dictionary") key = 'sample' # check if key exists in dictionary by checking if get() returned default value if word_freq.get(key, -1) != -1: print(f"Yes, key: '{key}' exists in dictionary") else: print(f"No, key: '{key}' does not exists in dictionary") print('python check if key in dict using keys()') key = 'test' if key in word_freq.keys(): print(f"Yes, key: '{key}' exists in dictionary") else: print(f"No, key: '{key}' does not exists in dictionary") print('python check if key in dict using try/except') print('python check if key in dictionary using try/except') key = 'test' # check if dictionary has key in python if check_key_exist(word_freq, key): print(f"Yes, key: '{key}' exists in dictionary") else: print(f"No, key: '{key}' does not exists in dictionary") print('check if key not in dictionary in python using if not in statement') key = 'sample' # Check if key not in dict python if key not in word_freq: print(f"No, key: '{key}' does not exists in dictionary") else: print(f"Yes, key: '{key}' exists in dictionary") print('check if key not in dictionary in python using has_keys') if __name__ == '__main__': main()
Output
*** Python: check if key in dictionary using if-in statement*** Yes, key: 'test' exists in dictionary No, key: 'sample' does not exists in dictionary *** Python: check if dict has key using get() function *** No, key: 'sample' does not exists in dictionary No, key: 'sample' does not exists in dictionary python check if key in dict using keys() Yes, key: 'test' exists in dictionary python check if key in dict using try/except python check if key in dictionary using try/except Yes, key: 'test' exists in dictionary check if key not in dictionary in python using if not in statement No, key: 'sample' does not exists in dictionary check if key not in dictionary in python using has_keys
In this tutorial, we will learn how to check if a value exists in the dictionary.
In the Python programming language, List, Tuple, and Set represent a group of individual objects as a single entity. If we want to represent a group of objects as key-value pairs then we should go for the Dictionary concept.
We can check whether a value exists or not by getting values from the dictionary using the values()
, items()
, get()
, by accessing the keys of the dictionary and using the membership operator.
Example: Using values() method
The below example shows how to get values from the built-in method values()
.
dict_1={100:"python",200:"Java",300:"Ruby",400:"C",500:"C++",600:"R"}
x=dict_1.values()
print("values present in dictionary dict_1 are:",x)
print("The type of x is:",type(x))
# we can iterate keys values:
for k in dict_1.values():
print("The value present in dictionary dict_1 is:",k)
Once we run the code, it shows the following result.
values present in dictionary dict_1 are: dict_values([‘python’, ‘Java’, ‘Ruby’, ‘C’, ‘C++’, ‘R’])
The type of x is: <class ‘dict_values’>
The value present in dictionary dict_1 is: python
The value present in dictionary dict_1 is: Java
The value present in dictionary dict_1 is: Ruby
The value present in dictionary dict_1 is: C
The value present in dictionary dict_1 is: C++
The value present in dictionary dict_1 is: R
Example: Using items() method
The below example shows how to get values from the built-in method items()
.
#dictionary with key value pairs
dict_1={100:"python",200:"Java",300:"Ruby"}
# Getting keys using items() method
x=dict_1.items()
print(x)
for k,v in x:
print("From the dict_1,the value element is:",v)
Once we run the code, it shows the following result.
dict_items([(100, ‘python’), (200, ‘Java’), (300, ‘Ruby’)])
From the dict_1, the value element is: python
From the dict_1, the value element is: Java
From the dict_1, the value element is: Ruby
Example: Using get() method
The below example shows how to get values from the built-in method items()
. If the specified key is not present in the dictionary, it returns none.
#dictionary with key value pairs
dict_1={100:"python",200:"Java",300:"Ruby"}
# Getting keys using get() method
x=dict_1.get(100,"Python")
print(x)
y=dict_1.get(100)
print(y)
z=dict_1.get("Java")
print(z)
a=dict_1.get("R")
print(a)
Once we run the code, it shows the following result.
python
python
None
None
Example: We can get values directly by accessing keys
The below example shows how to get values directly by accessing keys.
#dictionary with key value pairs
dict_1={100:"python",200:"Java",300:"Ruby"}
print("The values are:")
print(dict_1[100])
print(dict_1[200])
print(dict_1[300])
Once we run the code, it shows the following result.
The values are:
python
Java
Ruby
Following are the other methods to check if a specific value exists in a dictionary or not.
Example: Using Membership operator
From the previous example we learned how to get values from the dictionary using the values()
method. In the same way, we can check if the value is present in a dictionary or not.
In the below example, we are taking the input from the user to check value is in a dictionary or not.
Using the values()
method in the if statement, we are getting the values, and using the membership operator we are checking the value from the user input is in a dictionary or not.
value=input("Enter the value element to be check:")
print("The value element to be checked is:",value)
dict_1={100:"python",200:"Java",300:"Ruby",400:"C",500:"C++",600:"R"}
if value in dict_1.values():
print("The specifed value is present in dictionary")
else:
print("The specified value is not present in dictionary")
Once we run the code, it shows the following result.
Enter the value element to be check: python
The value element to be checked is: python
The specified value is present in the dictionary
Example: Using the items() method
The below example is similar to the previous example. Instead of the value() method, we are using the item()
method to get the values.
We can check values present in a dictionary or not using the items()
method.
value=input("Enter the value element to be check:")
print("The value element to be checked is:",value)
dict_1={100:"python",200:"Java",300:"Ruby",400:"C",500:"C++",600:"R"}
for k,v in dict_1.items():
if v==value:
print("The specifed value is present in dictionary")
Once we run the code, it shows the following result.
Enter the value element to be check: Java
The value element to be checked is: Java
The specified value is present in the dictionary
Conclusion
In this tutorial, we learned how to get values from the dictionary from the built-in functions and how to check if a specific key exists in a dictionary or not.
In this Python dictionary tutorial, we will discuss the Python dictionary contains. Here we will also cover the below examples:
- Python dictionary contains value
- Python dictionary contains Key
- Python dictionary contains list as value
- Python dictionary contains key example
- Python dictionary contains key value pair
- Python dictionary contains another dictionary
- Python dictionary contains element
- Python dictionary contains multiple keys
- Python dictionary contains duplicate keys
- Python dictionary key contains string
- Let us see how to check if a key/value pair contains in the Python dictionary.
- The easiest way to check if a key/value pair exists in a dictionary is to use the in operator. To do this task we can specify key/value pairs in a Python tuple. To check if a key/value pair does not exist in the dictionary we can use not in operator.
Source Code:
my_dict = {"e":4,"l":6,"q":5}
print(('e', 4) in my_dict.items())
In the above code, we will first initialize a dictionary ‘my_dict’, assign a key-value element, and display the result.
Here is the execution of the following given code
Read: Python for loop index
Python dictionary contains value
- Here we can see how to check if the value contains in a Python dictionary.
- To solve this problem we can use values() and the if-in statement method. In Python, the values() method returns a view object that displays all the values connected with keys. To check if our value exists in the iterable sequence or not we can use the ‘in’ operator.
- There are various method to perform this task
- By using get and key method
- By using in operator
Syntax:
If value in dict:
# dictionary contains(True)
else:
# dictionary not contains
Source code:
The source code below represents the operation of the if-in statement to check if the value contains in a dictionary or not.
new_dict = {"Ethan":78,"Mason":98,"Benjamin":72}
new_val = 98
if new_val in new_dict.values():
print(f"True, Value contains in dictionary:",new_val)
else:
print(f"False, Value does not contains in dictionary:",new_val)
As you can see value ’98’ contains in a dictionary therefore the if-in statement comes true.
Here is the Screenshot of the following given code
Read Python ask for user input
By using get() and key method
In Python the get function accepts a key, In this case, the key is a built-in function in Python and it will always return the value of the given key. If the value does not contain in the dictionary it will return None.
Example:
ne_dictionary = {12:"OLiva",17:"Marry",16:"Gilchrist"}
key = 12
if ne_dictionary.get(key) == None:
print('Value not contain')
else:
print('Value contain')
Output:
By using in operator
Let us see how to check if the value contains in the Python dictionary by using in operator method.
Source Code:
ne_dictionary = {"q":12,"i":74,"p":23,"x":123}
print(74 in ne_dictionary.values())
.Here is the execution of the following given code
Read: Python dictionary comprehension
Python dictionary contains key
- To use in operator with if statement we can check whether the key is contained in a dictionary or not in Python.
- In Python, the in operator basically checks if a key contains in a dictionary or not. if the key does not exist we cannot use the in-operator.
- In this example, we will give the condition if the key exists the result will display ‘True’ otherwise if not exist it will return ‘False’.
Syntax:
If key in dict:
#key exist in dictionary (True)
else:
#key does not exist in dictionary(False)
Source Code:
my_dictionary = {"Samuel":19,"Mathew":37,"Micheal":92}
exist_ke = 'Potter'
if exist_ke in my_dictionary:
print("True, key contains in dict.n" )
else:
print("False, key does not contains in dict.n")
In the above code, you can see that we have used an if-in statement along with the operator. Now in this example, we do not have a ‘potter’ key in our dictionary, thus it will display the result ‘key does not contain in dict’.
Execution:
Another example to check if key contains in a dictionary using has_key() method
To check whether a particular key is present in the dictionary, we can easily use the function has_key(). This method returns true if the key exists otherwise it returns false.
Syntax:
dict.has_keys()
Note: In Python, the has_key() function is only available in Python 2.7 version.
Example:
country_dict = {"cuba":52,"Estonia":47,"Kenya":82}
new_key = 'Kenya'
if country_dict.has_key(new_key):
print("True, key contains:")
else:
print("False,key not contain")
Here is the output of the following given code
Read: Python dictionary find a key by value
Python dictionary contains list as value
Let us see how to check if the list as a value contains in the dictionary by using in operator method in Python.
Source code:
you_dict = {"o":[1,14,2,],"m":[10,74,90],"n":[23,47,86]}
print([10,74,90] in you_dict.values())
In the above code first, we will initialize a dictionary and assign their elements in the form of key-value pairs. But in this case, the value is in the list form. Now we will check the condition if the value contains in a dictionary or not.
Implementation:
Read: Python convert dictionary to list
Python dictionary contain key example
- let us see how to check if the key contains in a Python dictionary.
- To perform this task we can apply the python keys() method. This method helps the user to check if the key contains in an existing dictionary.
- This method takes no parameters and always returns a list of all the keys which is available in a dictionary. In this example, we can use the if- statement along with the keys() method to differentiate with the ‘new_key’ variable. If it is existing in the dictionary then it will display the result ‘True’ otherwise it will jump the statement in the else part and returns ‘False’.
Source Code:
stud_dict= {"Gayle":34,"Siemens":59,"pollard":70}
new_key = 'Siemens'
if new_key in stud_dict.keys():
print("True, it contains:")
else:
print("False, it does not contains")
Here is the Screenshot of the following given code
Another example to check if the key exists in a dictionary by using the get() method
In Python, the get() method accepts the only key parameter and returns the value along with the key. If the key does not exist in the dictionary by default it will return the None value.
Syntax:
dict.get
(
Key,
default=None
)
Example:
stud_dict= {"Oliver":943,"potter":178,"hemsworth":36}
se_ne_key = 'George'
if stud_dict.get(se_ne_key) == None:
print('Key not exist')
else:
print('Key exist')
Here is the implementation of the following given code
Read: Python dictionary remove
Python dictionary contains key-value pair
- Here we can see how to check if a key/value pair contains in a Python dictionary. The simplest way to check if a key/value pair exists in a dictionary is to use the in operator.
Example:
new_dict={'Brazil':63,'Bermuda':71,'Ireland':189}
new_key,new_value = 'Bermuda',71
z = new_key in new_dict and new_value == new_dict[new_key]
print("Keys and value exist in dictionary:",z)
Here is the execution of the following given code
Python dictionary contains another dictionary
- Here we can see if one dictionary is a subset of another dictionary in Python.
- To perform this task we can use the items() method along with <=operator. In Python, the items() method returns a list containing the key-value pair.
- The <= operator compares the values and returns the result in the form of ‘True’ or ‘False’.
Source Code:
Country_dict = {'Kuwait' : 523, 'Jordan' : 876, 'Laos' : 921, 'Libya' : 167, 'Malta' : 763}
sub_country = {'Jordan' : 876, 'Libya' : 167, 'Malta' : 763}
print("Country names:",Country_dict)
print("Another dictionary:",sub_country)
new_output = sub_country.items() <= Country_dict.items()
print("Dictionary contains in another dict: ",new_output)
Here is the Screenshot of the following given code
Read: Python dictionary length
Python dictionary contain elements
- To check if elements contain in a dictionary or not we can use the in operator in Python.
Example:
new_dictionary = {"z":18,"a":14,"c":10}
print(('a', 14) in new_dictionary.items())
Here is the implementation of the following given code
Read: Python Dictionary index
Python dictionary contains multiple keys
- Let us see how to check if multiple keys contained in a dictionary in Python.
- To perform this task we can easily use the issubset() method. This method is a in-built function in Python and it returns true if all the elements of dict1 are contained in original dictionary.
Code:
Food_dict = {"Italian" : 25, "Mexican" : 31, "Chinese" :27}
# multiple keys
new_dict = set(['Italian', 'Mexican'])
print(new_dict.issubset(Food_dict.keys()))
In the above code first, we will initialize a dictionary and declare a ‘new_dict’ variable and assign the set of keys that we want to compare and display the output.
Here is the implementation of the following given code
Read: Python dictionary initialize
Python dictionary contains duplicate keys
In Python to check if duplicate keys are contained in a dictionary. we can easily use the method chain and set(). This method takes a series of iterable items and returns a single iterable.
Source Code:
from itertools import chain
new_dictionary = {'m':87, 'a':29, 'q':29, 'w':34}
find_key = {}
for new_k, new_val in new_dictionary.items():
find_key.setdefault(new_val, set()).add(new_k)
output = set(chain.from_iterable(
new_val for new_k, new_val in find_key.items()
if len(new_val) > 1))
print("Duplicate values", output)
Here is the Screenshot of the following given code
Read: Python dictionary filter
Python dictionary key contains string
To perform this task we can apply the python keys() method in Python. This method helps the user check if the key contains a string in an existing dictionary.
Source Code:
new_dict= {"Andrew":146,"Hayden":190,"James":370}
new_key = 'Hayden'
if new_key in new_dict.keys():
print("True, string contains:")
else:
print("False, string does not contains")
Output:
You may also like to read:
- Python loop through a list
- Python copy file
- Python File methods
- Union of sets Python
- Python write a list to CSV
In this Python tutorial, we have discussed the Python dictionary contains. Here we have also covered the following examples:
- Python dictionary contains value
- Python dictionary contains Key
- Python dictionary contains list as value
- Python dictionary contains key example
- Python dictionary contains key value pair
- Python dictionary contains another dictionary
- Python dictionary contains element
- Python dictionary contains multiple keys
- Python dictionary contains duplicate keys
- Python dictionary key contains string
Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.
- Use
get()
and Key to Check if Value Exists in a Dictionary - Use
values()
to Check if Specified Value Exists in a Dictionary - Check if Value Exists in a Dictionary if the Value Is a List
This tutorial shows how you can check a value if it exists within a Python dictionary. Here, we’ll cover relevant topics, such as searching for a value given by a key, searching for a specific value, and searching for a value that’s an object or a collection.
To start, you’d want to print True
if the value exists in the dictionary; otherwise, print False
.
Use get()
and Key to Check if Value Exists in a Dictionary
Dictionaries in Python have a built-in function key()
, which returns the value of the given key. At the same time, it would return None
if it doesn’t exist. You can use this function as a condition to determine whether or not a value exists within a dictionary.
Let’s first declare a simple dictionary with int
keys and string values.
simpDict = {
1: "Ant",
2: "Bear",
3: "Cat",
4: "Dog",
5: "Elephant"
}
If you want to look for the value using its key pair, then the key()
function is the way to go. For example, you want to search for any value with the 6 as their key; follow the code below.
if (simpDict.key(6) != None):
print("True")
else:
print ("False")
Since the simpDict
function doesn’t have the key 6, this block of code will output False
.
Use values()
to Check if Specified Value Exists in a Dictionary
Unlike the situation in looking for a specific value, looking for a key within a dictionary is very straightforward; you just have to use the keyword in
and the key you’re looking for in the dictionary.
This will output True
since key 3 exists. If we replace the number with a non-existent key, then it will output False
.
On the other hand, you can use the function values()
if you want to look for a specific value in the dictionary. The values()
command will return a list of all the values within a dictionary. Using values()
, you can utilize the in
keyword to the dictionary and the specified value. Let’s say you want to know if the value Elephant
is in the dictionary, execute the following code:
print ( "Elephant" in simpDict.values() )
This line will output True
since the word Elephant
exists in simpDict
on key 5.
In Python 2.X, there also are two other functions similar to values()
, they are the itervalues()
and viewvalues()
; these functions have been deprecated in the Python 3.X versions.
The itervalues()
and viewvalues()
commands will do the same task as the values()
command; however, different implementations, although very negligible, greatly affects the runtime.
print ( "Elephant" in simpDict.itervalues() )
print ( "Elephant" in simpDict.viewvalues() )
Both will return the same output as the values()
function. It’s important to note that redundancy is probably the primary reason why these functions have been deprecated from newer Python versions.
Now, what if the values of a dictionary are data structures like a list or an object? Let’s find out.
Check if Value Exists in a Dictionary if the Value Is a List
listDict = {1: ['a', 'b'],
2: ['b', 'c'],
3: ['c', 'd'],
4: ['d', 'e']}
Now, we have a dictionary with int
keys and a list of characters as values.
Let’s say we want to search if the list ['c', 'd']
exists in the dictionary.
print( ['c', 'd'] in listDict.values() )
The resulting output would be True
; this confirms that comparing collections by iterating the dictionary also works.
But what if you want to check if a value within a list value exists in the dictionary? To solve this, just loop over the values and use the in
keyword on the list, instead of on the dictionary.
For example, you want to check whether the character 'e'
exists within the values in this list or not. Here’s the code to execute for that:
tof = False
for value in listDict.values():
if ('e' in value):
tof = True
break
print(tof)
The output will print out True
since 'e'
exists in the dictionary.
In summary, use the function values()
to iterate over the values and compare whether the value you’re looking for exists within the list of values. This helps when you want to check if a specified value exists in a dictionary.