我正在尝试检查字典中是否存在特定值。似乎对于键,一个简单的 if 'x' in 'dictionary'
语句有效,但不适用于值。
dictionary = {
'First': '1',
'Second': '2',
'Third': '3'
}
if 'First' in dictionary:
print('First is here')
if '1' in dictionary:
print('1 is here')
所以明显的逻辑错误是输出只显示:
First is here
如有任何建议,我们将不胜感激,谢谢。
最佳答案
如果你想访问字典的值,你需要调用dict.values
:
if '1' in dictionary.values():
不需要调用dict.keys
然而:
if 'First' in dictionary.keys():
因为 in
运算符遍历字典,生成它的键。
关于python - 如何测试/搜索字典中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24312966/