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

Key with multiple values - check if value is in dictionary python

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

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

你的值是一个列表!

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

应该很简单:

>>> d = { 'a': ['spam', 'eggs'], 'b': ['foo', 'bar'] }
>>> 'eggs' in d.get('a')
True

您可以遍历字典。 如果您的字典如下所示:

my_dictionary = { 'names': ['john', 'doe', 'jane'], 'salaries': [100, 200, 300] }

然后您可以执行以下操作:

for key in my_dictionary:
    for value in my_dictionary[key]:
        print value

您自然可以搜索而不是打印。像这样:

for key in my_dictionary:
    for value in my_dictionary[key]:
        if "keyword" in value:
            print "found it!"

可能有更短的方法来执行此操作,但这也应该有效。

如果你只是想检查一个值是否存在而不需要知道它所属的键等等,你可以这样做:

if 'the' in str(d.values())

或者对于单行,你可以使用过滤功能

if filter(lambda x: 'eggs' in x, d.values()) # To just check
filter(lambda x: 'eggs' in d[x] and x, d) # To get all the keys with the value

我喜欢写作

if 0 < len([1 for k in d if 'the' in d[k]]):
    # do stuff

或等效

if 0 < len([1 for _,v in d.iteritems() if 'the' in v]):
    # do stuff