We use dictionaries to store and manipulate key-value pairs in a python program. Sometimes, we need to check if a value exists in a dictionary or not. In this python tutorial, we will discuss different ways to check if a value exists in a python dictionary. Here, while checking for the values we might have the keys available with us or otherwise. We will discuss how we can check if a value is present in a dictionary in both cases.
- Check if a Value Exists in a Dictionary When We Have the Keys Available
- Check if a Value Exists in a Dictionary When We Have Keys Unavailable
- Conclusion
Check if a Value Exists in a Dictionary When We Have the Keys Available
When we have the keys of the dictionary, we can use the subscript operator or the get()
method to check if a given value exists in the dictionary. Let us discuss each approach one by one.
Check if a Value Exists in a Dictionary Using the Subscript Operator
The Subscript Operator
When we have a key and we want to check if a value exists in the dictionary, we can use the subscript operator. For this, we can use square brackets to retrieve the value associated with the key using the following syntax.
value=dict[key_val]
Here, dict
is the name of the dictionary and key_val
is the key. After execution, the above statement returns the value associated with the key in the dictionary. You can observe this in the following code example.
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
key = "name"
value = myDict[key]
print("The value associated with the key \"{}\" is \"{}\".".format(key, value))
Output:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The value associated with the key "name" is "Python For Beginners".
Here, we have first created a dictionary name myDict
with keys name
, url
, acronym
, and type
. After that, we have retrieved the value associated with the key ‘name
‘ using the subscript operator. Here, the program works normally.
However, there may be situations where the key provided to the subscript operator might not be present in the dictionary. In such a case, the program will run into the KeyError
exception as shown below.
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
key = "class"
value = myDict[key]
print("The value associated with the key \"{}\" is \"{}\".".format(key, value))
Output:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/webscraping.py", line 5, in <module>
value = myDict[key]
KeyError: 'class'
Here, the key ‘class
‘ doesn’t exist in the dictionary. Therefore, the program runs into the KeyError
exception.
In such a case, the program will get terminated abruptly and any work done during the program execution will get lost. In these cases, you can use the python try-except blocks to handle the exception as shown below.
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
key = "class"
try:
value = myDict[key]
print("The value associated with the key \"{}\" is \"{}\".".format(key, value))
except KeyError:
print("The key '{}' is not present in the dictionary.".format(key))
Output:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The key 'class' is not present in the dictionary.
In the above example, the KeyError
exception is raised in the try block. In the except block, we catch the exception and terminate the program normally by printing the appropriate message for the user.
When We Have a Single Input Key
To check if a value exists in a dictionary using the subscript notation, we will obtain the value associated with the key name in the dictionary. After that, we will check if the obtained value is equal to the given value whose presence we are checking.
If both the values match, we will say that the input value pair is present in the dictionary. Otherwise, not.
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
key = "name"
input_value = "Python For Beginners"
print("Input key is:", key)
print("Input value is:", input_value)
try:
value = myDict[key]
if value == input_value:
print("'{}' is present in the dictionary".format(input_value))
else:
print("'{}' is not present in the dictionary".format(input_value))
except KeyError:
print("The key '{}' is not present in the dictionary.".format(key))
Output:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
Input key is: name
Input value is: Python For Beginners
'Python For Beginners' is present in the dictionary
We have been provided the key ‘name
‘ in the above code. Along with that, we have the value 'Python For Beginners
‘ whose presence we have to check. As we have only one key, in this case, we have just obtained the value associated with the given key. After that, we compared the obtained value with the given input value to check if the input value exists in the dictionary.
When We Have Multiple Input Keys
Now, we have multiple keys and we need to check if a value exists in the dictionary. Here, we need to perform the entire operation discussed above for each key.
In this approach, we will iterate over the list of keys given as input using a for loop. For each key present in the list, we will retrieve the associated value and compare it with the input value. If both the values match, we will say that the input value is present in the dictionary. At the same time, we will break out of the for loop.
If none of the keys have an associated value equal to the input value, we will say that the value is not present in the dictionary. You can observe the entire process in the following example.
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
keys = ["name", 'type']
input_value = "Python For Beginners"
print("Input keys are:", keys)
print("Input value is:", input_value)
valueFound = False
for key in keys:
try:
value = myDict[key]
if value == input_value:
print("'{}' is present in the dictionary".format(input_value))
valueFound = True
break
else:
continue
except KeyError:
print("The key '{}' is not present in the dictionary.".format(key))
if not valueFound:
print("'{}' is not present in the dictionary".format(input_value))
Output:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
Input keys are: ['name', 'type']
Input value is: Python For Beginners
'Python For Beginners' is present in the dictionary
While using the subscript operator, the program runs into the KeyError
exception if the key doesn’t exist in the dictionary. Handling the KeyError
exception is costly in terms of time and memory. Therefore, we can avoid the exception by checking the presence of a key using the keys()
method or by using the get()
method.
Check if a Value Exists in a Dictionary Using the keys() Method
The keys()
method, when invoked on a dictionary, returns a dict_keys
object containing the keys of the dictionary. You can observe this in the following result.
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
keys = myDict.keys()
print("The keys in the dictionary are:")
print(keys)
Output:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The keys in the dictionary are:
dict_keys(['name', 'url', 'acronym', 'type'])
When We Have a Single Input Key
To check if a value exists in a dictionary using the keys()
method, we will first obtain the list of keys of the dictionary.
After that, we will check for the presence of a particular key to ascertain that the key is a valid key for the existing dictionary. If the input key is present in the list of keys, we will proceed to check if the given value exists in the dictionary.
For a valid key, to check if the value exists in the dictionary, we will obtain the value associated with the key of the dictionary. After that, we will check if the obtained value is equal to the given value whose presence we are checking. If both the values match, we will say that the value is present in the dictionary. Otherwise not.
You can observe this in the following example.
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
keys = myDict.keys()
print("The keys in the dictionary are:")
print(keys)
key="name"
input_value="Python For Beginners"
if key in keys:
value = myDict[key]
if value == input_value:
print("'{}' is present in the dictionary.".format(input_value))
else:
print("'{}' is not present in the dictionary.".format(input_value))
else:
print("The key '{}' is not present in the dictionary.".format(key))
Output:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The keys in the dictionary are:
dict_keys(['name', 'url', 'acronym', 'type'])
'Python For Beginners' is present in the dictionary.
When We Have Multiple Input Keys
When we have more than one key, we can use a for loop to iterate over the list of keys. We will repeat the entire process for each given key. If none of the keys have the associated value the same as the given value, we will say that the value is not present in the dictionary. You can observe this entire process in the below example.
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
keys = myDict.keys()
print("The keys in the dictionary are:")
print(keys)
input_keys = ['Aditya',"name", 'type']
input_value = "Python For Beginners"
valueFound = False
for key in input_keys:
if key in keys:
value = myDict[key]
if value == input_value:
print("'{}' is present in the dictionary.".format(input_value))
valueFound = True
break
else:
continue
else:
print("The key '{}' is not present in the dictionary.".format(key))
if not valueFound:
print("'{}' is not present in the dictionary.".format(input_value))
Output:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The keys in the dictionary are:
dict_keys(['name', 'url', 'acronym', 'type'])
The key 'Aditya' is not present in the dictionary.
'Python For Beginners' is present in the dictionary.
Check if a Value Exists in a Dictionary Using the get() Method
Instead of using the keys()
method to check for the existence of a key and then obtain the value using the subscript operator, we can use the get()
method to check if a value is present in a dictionary.
The get()
method, when invoked on a dictionary, accepts a key as an input argument. If the key is present in the dictionary, it returns the value associated with the key as shown below.
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
key = "name"
print("THe key is '{}'.".format(key))
value = myDict.get(key)
print("THe value is '{}'.".format(value))
Output:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
THe key is 'name'.
THe value is 'Python For Beginners'.
If the given key isn’t present in the dictionary, the get()
method returns the default value None
. You can observe this in the following example.
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
key = "website"
print("THe key is '{}'.".format(key))
value = myDict.get(key)
print("THe value is '{}'.".format(value))
Output:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
THe key is 'website'.
THe value is 'None'.
When We Have a Single Input Key
To check if a value exists in the dictionary using the get function, we will obtain the value associated with the given key. After that, we will check if the obtained value is equal to the given value. If yes, we will say that the value is present in the dictionary. Otherwise, not.
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
key = "name"
input_value = "Python For Beginners"
print("The key is '{}'.".format(key))
print("The input value is '{}'.".format(input_value))
value = myDict.get(key)
if value is None:
print("The key '{}' is not present in the dictionary.".format(key))
elif value == input_value:
print("The value '{}' is present in the dictionary.".format(input_value))
else:
print("The value '{}' is not present in the dictionary.".format(input_value))
Output:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The key is 'name'.
The input value is 'Python For Beginners'.
The value 'Python For Beginners' is present in the dictionary.
When We Have Multiple Input Keys
If we are given multiple keys, we can use a for loop to iterate over the list of keys. While iteration, we can check if the input value is present for each key. If None of the given keys has the associated value equal to the given value, we will say that the value is not present in the dictionary. You can observe this in the following example.
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
keys = ['Aditya', "name", 'url']
input_value = "Python For Beginners"
print("The input keys are '{}'.".format(keys))
print("The input value is '{}'.".format(input_value))
valueFound=False
for key in keys:
value = myDict.get(key)
if value is None:
print("The key '{}' is not present in the dictionary.".format(key))
elif value == input_value:
print("The value '{}' is present in the dictionary.".format(input_value))
valueFound=True
break
if not valueFound:
print("The value '{}' is not present in the dictionary.".format(input_value))
Output:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The input keys are '['Aditya', 'name', 'url']'.
The input value is 'Python For Beginners'.
The key 'Aditya' is not present in the dictionary.
The value 'Python For Beginners' is present in the dictionary.
Till now, we have discussed different scenarios to check if a value exists in a dictionary or not when we are given some keys of the dictionary.
Let us now discuss different ways to check if a value exists in a dictionary or not when keys are not given and only a value is given whose presence we have to check.
Check if a Value Exists in a Dictionary When We Have Keys Unavailable
Check if a Value Exists in a Dictionary Using the keys() Method
To check if a value exists in a dictionary using the keys()
method, we will first obtain the list of keys by executing the keys()
method on the dictionary.
After that, we will use the subscript operator to obtain the values of the dictionary associated with each key present in the list of keys. If any of the obtained values is equal to the value whose presence we are checking, we will say that the value is present in the dictionary. Otherwise not. You can observe this in the following example.
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
input_value = "Python For Beginners"
print("The input value is '{}'.".format(input_value))
keys = myDict.keys()
isPresent = False
for key in keys:
value = myDict[key]
if value == input_value:
print("'{}' is present in the dictionary.".format(input_value))
isPresent = True
break
else:
continue
if not isPresent:
print("'{}' is not present in the dictionary.".format(input_value))
Output:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The input value is 'Python For Beginners'.
'Python For Beginners' is present in the dictionary.
Check if Multiple Values Exist in a Dictionary Using the keys() Method
If we need to check if multiple values are present in the dictionary, we will first obtain a list of values using the get()
method and the keys()
method as shown below.
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
keys = myDict.keys()
print("The keys of the dictionary are:")
print(keys)
values = []
for key in keys:
value = myDict.get(key)
values.append(value)
print("The obtained values are '{}'.".format(values))
Output:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The keys of the dictionary are:
dict_keys(['name', 'url', 'acronym', 'type'])
The obtained values are '['Python For Beginners', 'pythonforbeginners.com', 'PFB', 'python blog']'.
Here, we have first obtained the keys of the dictionary using the keys()
method. After that, we created an empty list to store the values of the dictionary. Then, we obtained the value associated with each key in the dictionary using the get()
method and stored it in the list.
After obtaining the list of values in the dictionary, we will check if each input value is present in it. For this, we can use a for loop with the membership operator as shown below.
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
keys = myDict.keys()
print("The keys of the dictionary are:")
print(keys)
input_values = ["Python For Beginners", "PFB", 'Aditya']
print("The input values are:", input_values)
values = []
for key in keys:
value = myDict.get(key)
values.append(value)
print("The obtained values are '{}'.".format(values))
for value in input_values:
if value in values:
print("The value '{}' is present in the dictionary.".format(value))
else:
print("The value '{}' is not present in the dictionary.".format(value))
Output:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The keys of the dictionary are:
dict_keys(['name', 'url', 'acronym', 'type'])
The input values are: ['Python For Beginners', 'PFB', 'Aditya']
The obtained values are '['Python For Beginners', 'pythonforbeginners.com', 'PFB', 'python blog']'.
The value 'Python For Beginners' is present in the dictionary.
The value 'PFB' is present in the dictionary.
The value 'Aditya' is not present in the dictionary.
Check if a Value Exists in a Dictionary Using the values() Method
The values()
method, when invoked on a dictionary, returns a copy of the dict_values
object containing the values of a dictionary. You can observe this in the following example.
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
values = myDict.values()
print("The values in the dictionary are:")
print(values)
Output:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The values in the dictionary are:
dict_values(['Python For Beginners', 'pythonforbeginners.com', 'PFB', 'python blog'])
To check if a value exists in a dictionary using the values()
method, we will first obtain the dict_values
object containing the values of the dictionary by invoking the values()
method on the dictionary.
After that, we will iterate through the list of values to check whether the value given as the user input is present in the list of values or not. If yes, we will say that the value is present in the dictionary. Otherwise not.
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
values = myDict.values()
print("The values in the dictionary are:")
print(values)
input_value = "Python For Beginners"
print("The input value is '{}'.".format(input_value))
isPresent = False
for value in values:
if value == input_value:
print("'{}' is present in the dictionary.".format(input_value))
isPresent = True
break
else:
continue
if not isPresent:
print("'{}' is not present in the dictionary.".format(input_value))
Output:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The values in the dictionary are:
dict_values(['Python For Beginners', 'pythonforbeginners.com', 'PFB', 'python blog'])
The input value is 'Python For Beginners'.
'Python For Beginners' is present in the dictionary.
Instead of using the for loop to iterate through the list of values, we can use the membership operator “in
” to check if the given value is present in the list of values or not. The syntax of the in
operator is as follows.
element in container_object
The in
operator is a binary operator that takes an element as its first operand and a container object or an iterator as its second operand. After execution, it returns True
if the element is present in the container object or the iterator. Otherwise, it returns False
.
To check if the given value exists in the dictionary, we will check if the value exists in the list of values returned by the values()
method using the membership operator as shown in the following example.
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
values = myDict.values()
print("The values in the dictionary are:")
print(values)
input_value = "Python For Beginners"
print("The input value is '{}'.".format(input_value))
if input_value in values:
print("'{}' is present in the dictionary.".format(input_value))
else:
print("'{}' is not present in the dictionary.".format(input_value))
Output:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The values in the dictionary are:
dict_values(['Python For Beginners', 'pythonforbeginners.com', 'PFB', 'python blog'])
The input value is 'Python For Beginners'.
'Python For Beginners' is present in the dictionary.
Check if Multiple Values Exist in a Dictionary Using the values() Method
If we are given multiple values to check for their presence, we will use a for loop with the membership operator and the values()
method to check for the presence of the keys. Here, we will iterate over the list of input values using the for loop. While iteration, we will check if the current value is present in the list of values obtained using the values()
method. If yes, we will print that the value is present in the dictionary. Otherwise not. You can observe this in the following example.
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
input_values = ["Python For Beginners", "PFB", 'Aditya']
print("The input values are:", input_values)
values = myDict.values()
for value in input_values:
if value in values:
print("The value '{}' is present in the dictionary.".format(value))
else:
print("The value '{}' is not present in the dictionary.".format(value))
Output:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The input values are: ['Python For Beginners', 'PFB', 'Aditya']
The value 'Python For Beginners' is present in the dictionary.
The value 'PFB' is present in the dictionary.
The value 'Aditya' is not present in the dictionary.
Check if a Value Exists in a Dictionary Using The viewvalues() Method
If you are using Python version 2.x, instead of using the values()
method, you can use the viewvalues()
method to check if a value exists in a dictionary.
The viewvalues()
method, when invoked on a dictionary, returns a view of the dict_values
object containing a new view of the values in the dictionary as shown below.
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
values = myDict.viewvalues()
print("The values in the dictionary are:")
print(values)
Output:
The dictionary is:
{'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog', 'name': 'Python For Beginners'}
The values in the dictionary are:
dict_values(['pythonforbeginners.com', 'PFB', 'python blog', 'Python For Beginners'])
After obtaining the dict_values
object, we can check if the input value exists in the dictionary.
To check if a value exists in a dictionary using the viewvalues()
method, we will first obtain the dict_values
object by invoking the viewvalues()
method on the dictionary.
After that, we will iterate through the dict_values
object to check whether the value given as the user input is present in the list of values or not. If yes, we will say that the value is present in the dictionary. Otherwise not.
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
values = myDict.viewvalues()
print("The values in the dictionary are:")
print(values)
input_value = "Python For Beginners"
print("The input value is '{}'.".format(input_value))
isPresent = False
for value in values:
if value == input_value:
print("'{}' is present in the dictionary.".format(input_value))
isPresent = True
break
else:
continue
if not isPresent:
print("'{}' is not present in the dictionary.".format(input_value))
Output:
The dictionary is:
{'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog', 'name': 'Python For Beginners'}
The values in the dictionary are:
dict_values(['pythonforbeginners.com', 'PFB', 'python blog', 'Python For Beginners'])
The input value is 'Python For Beginners'.
'Python For Beginners' is present in the dictionary.
Instead of using the for loop, we can also check the presence of the input value in the dict_values
object using the membership test as shown below.
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
values = myDict.viewvalues()
print("The values in the dictionary are:")
print(values)
input_value = "Python For Beginners"
print("The input value is '{}'.".format(input_value))
if input_value in values:
print("'{}' is present in the dictionary.".format(input_value))
else:
print("'{}' is not present in the dictionary.".format(input_value))
Output:
The dictionary is:
{'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog', 'name': 'Python For Beginners'}
The values in the dictionary are:
dict_values(['pythonforbeginners.com', 'PFB', 'python blog', 'Python For Beginners'])
The input value is 'Python For Beginners'.
'Python For Beginners' is present in the dictionary.
Check if Multiple Values Exist in a Dictionary Using the viewvalues() Method
If we are given multiple values to check for their presence, we will use a for loop with the membership operator and the viewvalues()
method to check for the presence of the keys. Here, we will iterate over the list of input values using the for loop. While iteration, we will check if the current value is present in the list of values obtained using the viewvalues()
method. If yes, we will print that the value is present in the dictionary. Otherwise not. You can observe this in the following example.
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
values = myDict.viewvalues()
print("The values in the dictionary are:")
print(values)
input_values = ["Python For Beginners",'PFB','Aditya']
print("The input values are '{}'.".format(input_values))
for input_value in input_values:
if input_value in values:
print("'{}' is present in the dictionary.".format(input_value))
else:
print("'{}' is not present in the dictionary.".format(input_value))
Output:
The dictionary is:
{'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog', 'name': 'Python For Beginners'}
The values in the dictionary are:
dict_values(['pythonforbeginners.com', 'PFB', 'python blog', 'Python For Beginners'])
The input values are '['Python For Beginners', 'PFB', 'Aditya']'.
'Python For Beginners' is present in the dictionary.
'PFB' is present in the dictionary.
'Aditya' is not present in the dictionary.
Check if a Value Exists in a Dictionary Using the itervalues() Method
In python 2, we can also use the itervalues() method to check if a value exists in a dictionary or not.
The itervalues()
method, when invoked on a dictionary, returns an iterator with which we can iterate over the values in the dictionary.
To check if a value exists in a dictionary using the itervalues()
method, we will first obtain the iterator returned by the itervalues()
method by invoking it on the dictionary. After that, we can iterate through the iterator using a for loop and check if the input value is present in the iterator or not. If yes, we will say that the value is present in the dictionary. Otherwise not.
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
values = myDict.itervalues()
input_value = "Python For Beginners"
print("The input value is '{}'.".format(input_value))
isPresent = False
for value in values:
if value == input_value:
print("'{}' is present in the dictionary.".format(input_value))
isPresent = True
break
else:
continue
if not isPresent:
print("'{}' is not present in the dictionary.".format(input_value))
Output:
The dictionary is:
{'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog', 'name': 'Python For Beginners'}
The input value is 'Python For Beginners'.
'Python For Beginners' is present in the dictionary.
Instead of using the for loop, we can also check the presence of the input value in the dict_values
object using the membership test as shown below.
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
values = myDict.itervalues()
input_value = "Python For Beginners"
print("The input value is '{}'.".format(input_value))
if input_value in values:
print("'{}' is present in the dictionary.".format(input_value))
else:
print("'{}' is not present in the dictionary.".format(input_value))
Output:
The dictionary is:
{'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog', 'name': 'Python For Beginners'}
The input value is 'Python For Beginners'.
'Python For Beginners' is present in the dictionary.
Check if Multiple Values Exist in a Dictionary Using the itervalues() Method
If we are given multiple values to check for their presence, we will use a for loop with the membership operator and the itervalues()
method to check for the presence of the keys.
Here, we will iterate over the list of input values using the for loop. While iteration, we will check if the current value is present in the iterator of values obtained using the itervalues()
method. If yes, we will print that the value is present in the dictionary. Otherwise not. You can observe this in the following example.
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
values = myDict.itervalues()
input_values = ["Python For Beginners",'PFB','Aditya']
print("The input values are '{}'.".format(input_values))
for input_value in input_values:
if input_value in values:
print("'{}' is present in the dictionary.".format(input_value))
else:
print("'{}' is not present in the dictionary.".format(input_value))
Output:
The dictionary is:
{'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog', 'name': 'Python For Beginners'}
The input values are '['Python For Beginners', 'PFB', 'Aditya']'.
'Python For Beginners' is present in the dictionary.
'PFB' is not present in the dictionary.
'Aditya' is not present in the dictionary.
Conclusion
In this article, we have discussed various methods to check if a value is present in a dictionary. If you have the keys of the dictionary, you can use the approach using the get()
method to check if a value exists in a dictionary or not. If you don’t have the keys, you should use the approach using the values()
method in python 3.x. For Python version 2.x, you should use the approach with the itervalues()
method as it is the fastest among all the approaches.
I hope you enjoyed reading this article. To learn more about python programming, you can read this article on how to remove all occurrences of a character in a list in Python. You might also like this article on how to check if a python string contains a number.
Stay tuned for more informative articles.
Happy Learning!
The post Check if Value Exists in a Dictionary in Python appeared first on PythonForBeginners.com.