views:

73

answers:

3

I want test whether a string is present within any of the list values in a defaultdict.

For instance:

from collections import defaultdict  
animals = defaultdict(list)  
animals['farm']=['cow', 'pig', 'chicken']  
animals['house']=['cat', 'rat']

I want to know if 'cow' occurs in any of the lists within animals.

'cow' in animals.values()  #returns False

I want something that will return "True" for a case like this. Is there an equivalent of:

'cow' in animals.values()  

for a defaultdict?

Thanks!

+9  A: 

defaultdict is no different from a regular dict in this case. You need to iterate over the values in the dictionary:

any('cow' in v for v in animals.values())

or more procedurally:

def in_values(s, d):
    """Does `s` appear in any of the values in `d`?"""
    for v in d.values():
        if s in v:
            return True
    return False

in_values('cow', animals)
Ned Batchelder
A: 

you can flatten your list like

'cow' in [x for y in animals.values() for x in y]
Tumbleweed
A: 
any("cow" in lst for lst in animals.itervalues())
Dave Kirby