Skip to content Skip to sidebar Skip to footer

Search Python Dictionary Where Value Is List

If I had a dictionary where the value was set to a list by default, how could I go about searching all of these lists in the dictionary for a certain term? For Example: textbooks =

Solution 1:

[k for k, v in textbooks.iteritems() if 'red' in v]

It is Pythonic shorthand for

res = []
for key, val in textbooks.iteritems():
    if 'red' in val:
        res.append(key)

See list comprehension in Python documentation


Solution 2:

[key for key, corresponding_list in textbook.items() if 'red' in corresponding_list]

Post a Comment for "Search Python Dictionary Where Value Is List"