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.valu开发者_运维技巧es()
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)
any("cow" in lst for lst in animals.itervalues())
This example will flatten the list, checking each element and will return True or False as follows:
>>> from collections import defaultdict
>>> animals = defaultdict(list)
>>> animals['farm']=['cow', 'pig', 'chicken']
>>> animals['house']=['cat', 'rat']
>>> 'cow' in [x for y in animals.values() for x in y]
True
精彩评论