Skip to main content
 首页 » 编程设计

python之具有多个值的键之检查值是否在字典 python 中

2025年05月04日17zhenyulu

我有一个字典,其中包含为每个键存储的多个值的列表。我想检查给定值是否在字典中,但这不起作用:

if 'the' in d.values(): 
    print "value in dictionary" 

为什么它不能处理存储为列表的多个值?还有其他方法可以测试该值是否在字典中吗?

请您参考如下方法:

d.values() 通常以列表格式存储值。因此,您需要遍历列表内容并检查子字符串 the 是否存在。

>>> d = {'f':['the', 'foo']} 
>>> for i in d.values(): 
        if 'the' in i: 
            print("value in dictionary") 
            break 
 
 
value in dictionary