![](/img/trans.png)
[英]How can I check if a value exists in a dictionary, that's in a list within another dictionary?
[英]Check if specific text exists within a list stored as a dictionary's value
我将列表存储为字典中的值。 我正在尝试查看这些列表中是否存在特定值,但似乎无法弄清楚为什么以下内容不起作用。 按原样运行以下代码当前不会打印任何内容。
dictionaryTest = {'First': ['Test1', 'Test2'], 'Second': ['Test3'], 'Third': ['Test4', 'Test5', 'Test6', 'Test7']}
if 'Test6' in [i for i in dictionaryTest.values()]:
print('Found it!')
[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
)。 如果在任何子列表中找到该字符串,则采用该条件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.