深度阅读

How to check if a value exists in a Python dictionary?

作者
作者
2023年08月22日
更新时间
12.51 分钟
阅读时间
0
阅读量

To check if a value exists in a Python dictionary, you can use the in operator with the values() method, as shown below:

my_dict = {'key1': 10, 'key2': 45, 'key3': 23}
if 45 in my_dict.values():
    print("Value exists in dictionary")
else:
    print("Value does not exist in dictionary")

In this example, the in operator is used with my_dict.values() to check if the value 45 exists in the dictionary. If the value is found, the program will print “Value exists in dictionary”, otherwise it will print “Value does not exist in dictionary”.

Alternatively, you can also use a loop to iterate over the dictionary’s values and check if the value exists, as shown below:

my_dict = {'key1': 10, 'key2': 45, 'key3': 23}
value_exists = False
for value in my_dict.values():
    if value == 45:
        value_exists = True
if value_exists:
    print("Value exists in dictionary")
else:
    print("Value does not exist in dictionary")

In this example, a loop is used to iterate over the dictionary’s values and check if the value 45 exists. If the value is found, the program will set the value_exists variable to True. At the end of the loop, it checks the value of value_exists and prints the appropriate message.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。