首页 > 解决方案 > 检查存储为字典值的列表中是否存在特定文本

问题描述

我将列表存储为字典中的值。我正在尝试查看这些列表中是否存在特定值,但似乎无法弄清楚为什么以下内容不起作用。按原样运行以下代码当前不会打印任何内容。

dictionaryTest = {'First': ['Test1', 'Test2'], 'Second': ['Test3'], 'Third': ['Test4', 'Test5', 'Test6', 'Test7']}

if 'Test6' in [i for i in dictionaryTest.values()]:
    print('Found it!')

标签: pythonpython-3.xlistdictionary

解决方案


[i for i in dictionaryTest.values()]等于[['Test1', 'Test2'], ['Test3'], ['Test4', 'Test5', 'Test6', 'Test7']]等于['Test1', 'Test2', 'Test3', 'Test4', 'Test5', 'Test6', 'Test7'](并且in运算符不是递归的)。

您想要的是检查是否'Test6'在任何子项中,即:

if any('Test6' in items for items in dictionaryTest.values()):
    print('Found it!')

此解决方案遍历字典值(列表),并且对于每个值,它检查字符串'Test6'是否在子列表中(使用表达式'Test6' in items)。如果在任何子列表中找到该字符串,采用该条件。


推荐阅读