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!
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With