简体   繁体   中英

Check if specific text exists within a list stored as a dictionary's value

I have lists stored as the values in my dictionary. I'm trying to see if a specific value exists within any of those lists, but can't seem to figure out why the following wouldn't work. Running the below code as-is currently doesn't print anything.

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()] is equal to [['Test1', 'Test2'], ['Test3'], ['Test4', 'Test5', 'Test6', 'Test7']] but not to ['Test1', 'Test2', 'Test3', 'Test4', 'Test5', 'Test6', 'Test7'] (and the in operator is not recursive).

What you want is to check if 'Test6' is in any sub-item, that is:

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

This solution iterate over the dictionary values (which are list), and for each value, it check if the string 'Test6' is in the sub-list (using the expression 'Test6' in items ). If the string is found in any sub-list then the condition is taken.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM