How to Check if a Value is in a Dictionary in Python
This tutorial demonstrates how to check if a value exists in a Python dictionary. Here, we will cover related topics such as searching for a value given by a key, searching for a specific value, and searching for the value of an object or collection.
First, we need to print if the value exists in the dictionary True
; otherwise, print it False
.
get()
Check if a value exists in a dictionary
using and key
Dictionaries in Python have a built-in function key()
that returns the value for a given key. At the same time, if it does not exist, it will return None
. You can use this function as a condition to determine if a value exists in a dictionary.
Let's start by declaring a simple dictionary with int
keys and string values.
simpDict = {1: "Ant", 2: "Bear", 3: "Cat", 4: "Dog", 5: "Elephant"}
If you want to find a value using its key pair, then key()
the function is the best way to do it. For example, you want to search for any value with 6 as the key; follow the code below.
if simpDict.key(6) != None:
print("True")
else:
print("False")
Since simpDict
the function does not have a key 6, this code will output False
.
Use values()
to check if the specified value exists in the dictionary
Unlike the case of looking for a specific value, looking for a key in a dictionary is very straightforward; you just use the keyword in
and the key you want to look for in the dictionary.
print(3 in simpDict)
This will print True
, because the key 3 exists. If we replace the number with a key that doesn't exist, then it will print False
.
On the other hand, if you want to find a specific value in a dictionary, you can use the function values()
. values()
The command will return a list of all the values in the dictionary. Using values()
, you can in
query the dictionary and the specified value using the keyword. Suppose you want to know Elephant
whether the value is in the dictionary, execute the following code.
print("Elephant" in simpDict.values())
This line will be output True
because the word simpDict
exists in key 5 .Elephant
In Python 2.X, there are two values()
functions similar to , which are itervalues()
and viewvalues()
; these functions have been deprecated in Python 3.X version.
itervalues()
The and viewvalues()
commands will values()
accomplish the same task as the command; however, the different implementations, while very minor, significantly affect the runtime.
print("Elephant" in simpDict.itervalues())
print("Elephant" in simpDict.viewvalues())
Both return values()
the same output as the function. It is important to note that redundancy is probably the main reason these functions are deprecated from newer Python versions.
Now, what if the values in the dictionary are data structures like lists or objects? Let’s see.
If the value is a list, check if the value exists in a dictionary
listDict = {1: ["a", "b"], 2: ["b", "c"], 3: ["c", "d"], 4: ["d", "e"]}
Now, we have a int
dictionary with keys and a list of characters as values.
Suppose we want to search ['c', 'd']
whether a list exists in a dictionary.
print(["c", "d"] in listDict.values())
The resulting output will be True
; this confirms that iterating over dictionaries to compare sets is also possible.
But what if you want to check if one of the values in the list exists in the dictionary? To fix this, just loop over the values and use in
the keyword on the list instead of on the dictionary.
For example, you want to check 'e'
if a character is present in the value in this list. Here is the code to execute.
tof = False
for value in listDict.values():
if "e" in value:
tof = True
break
print(tof)
The output will print out True
as 'e'
exists in the dictionary.
In summary, use the function values()
to iterate over the values and compare if the value you are looking for exists in the list of values. This is helpful when you want to check if a specific value exists in a dictionary.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Enumerating a dictionary in Python
Publish Date:2025/05/05 Views:98 Category:Python
-
The function in Python enumerate() returns an object of enumeration type and adds a counter variable to iterate over a list or other type of collection. It makes looping over such objects easier. When we pass an enumeration object to list()
Changing dictionary values in Python
Publish Date:2025/05/05 Views:108 Category:Python
-
This tutorial will discuss various ways to change the value of a particular key in Python dictionary. We can do this by using the following methods. dict.update() method for cycle. Dictionary Unpacking dict.update() How to change dictionary
Finding the maximum value in a Python dictionary
Publish Date:2025/05/05 Views:60 Category:Python
-
This tutorial explains how to get a key with the maximum value in Python. Since the method has changed from the previous Python versions, it also lists some sample codes to clarify the concepts. Use operator.itemgetter() the method to get t
How to read input from stdin in Python
Publish Date:2025/05/05 Views:124 Category:Python
-
This tutorial discussed stdin the methods of reading input from in Python. You can read directly from the console or from a file name specified in the console. In Python, fileinput.input() use stdin fileinput We can use the read module in P
Maximum integer in Python
Publish Date:2025/05/05 Views:55 Category:Python
-
This tutorial will discuss the maximum integer value in different versions of Python and how we can get it. In Python 2, integers and long integers are different data types. The maximum value of an integer is 2 31 -1. If the value exceeds t
Get a list of time zones using Python
Publish Date:2025/05/05 Views:107 Category:Python
-
When developing real-world applications, software developers must ensure that the application can support users from both their own country and other parts of the world. Since most countries have different time zones and many people around
Convert NumPy array to list in Python
Publish Date:2025/05/05 Views:101 Category:Python
-
Lists and arrays are the two most basic and commonly used collection objects in Python. They are both mutable and are used to store a collection of elements under a common name and each element has a specific location that can be used to ac
Appending 2D Arrays in Python
Publish Date:2025/05/05 Views:64 Category:Python
-
In Python, we can have ND arrays. We can use NumPy module to process arrays in Python. This tutorial demonstrated the different methods you can use to append values to a two-dimensional array in Python. Use append() the function to ap
Sliding average of NumPy arrays in Python
Publish Date:2025/05/05 Views:190 Category:Python
-
The sliding average is often used to study time series data by calculating the average of data at a specific time interval. It is used to eliminate some short-term fluctuations and study data trends. When studying stock price trends, the si