Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Testing if a value is present in a defaultdict list

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!

like image 846
Jake Avatar asked Jul 16 '26 00:07

Jake


1 Answers

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)
like image 125
Ned Batchelder Avatar answered Jul 17 '26 13:07

Ned Batchelder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!