对 values() 使用 in 运算符
在这一步中,你将学习如何使用 in 运算符来检查字典的值中是否存在特定的值。in 运算符是 Python 中用于搜索和验证数据的强大工具。
从上一步继续,让我们使用相同的字典 my_dict。我们将检查值 "Alice" 是否存在于字典的值中。
修改你 ~/project 目录下的 dictionary_example.py 文件,加入以下代码:
## Create a dictionary
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
## Check if "Alice" is in the values
if "Alice" in my_dict.values():
print("Alice is in the dictionary values")
else:
print("Alice is not in the dictionary values")
保存对 dictionary_example.py 文件的更改并再次运行它:
python dictionary_example.py
输出应该是:
Alice is in the dictionary values
现在,让我们检查一个字典中不存在的值,例如 "Bob":
修改 dictionary_example.py 文件,检查 "Bob" 而不是 "Alice":
## Create a dictionary
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
## Check if "Bob" is in the values
if "Bob" in my_dict.values():
print("Bob is in the dictionary values")
else:
print("Bob is not in the dictionary values")
保存对 dictionary_example.py 文件的更改并再次运行它:
python dictionary_example.py
现在的输出应该是:
Bob is not in the dictionary values
in 运算符区分大小写。让我们检查 "alice"(小写)是否在字典的值中:
修改 dictionary_example.py 文件以检查 "alice":
## Create a dictionary
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
## Check if "alice" is in the values
if "alice" in my_dict.values():
print("alice is in the dictionary values")
else:
print("alice is not in the dictionary values")
保存对 dictionary_example.py 文件的更改并再次运行它:
python dictionary_example.py
现在的输出应该是:
alice is not in the dictionary values
这表明 in 运算符区分大小写,只有找到完全匹配的值时才会返回 True。