gpt4 book ai didi

python - 如何测试/搜索字典中的值

转载 作者:太空宇宙 更新时间:2023-11-04 09:02:02 25 4
gpt4 key购买 nike

我正在尝试检查字典中是否存在特定值。似乎对于键,一个简单的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com