4
votes

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 = {"math":("red", "large"), "history":("brown", "old", "small")} 

With more terms and cases where the same thing might occur again, how could I say find all of the keys in which their value is a list containing "red"? In my example above, the only one I'd want it to find would be "math".

2
Tip: it makes life easier on everyone if you give an SSCCE. In this case, that means actually putting the quotes around the strings to make your example valid Python syntax, so that people can quickly copy and paste your code into their consoles to play around with it. - DSM
Thanks, I've added the quotes for you. - cbbcbail

2 Answers

10
votes
[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

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