Reputation: 21145
Okay I'm trying to go for a more pythonic method of doing things.
How can i do the following:
required_values = ['A','B','C']
some_map = {'A' : 1, 'B' : 2, 'C' : 3, 'D' : 4}
for required_value in required_values:
if not required_value in some_map:
print 'It Doesnt Exists'
return False
return True
I looked at the builtin function all
, but I cant really see how to apply that to the above scenario.
Any suggestions for making this more pythonic?
Upvotes: 3
Views: 3382
Reputation: 5605
try a list comprehension:
return not bool([x for x in required_values if x not in some_map.keys()]) (bool conversion for clarity)
or return not [x for x in required_values if x not in some_map.keys()] (i think the more pythonic way)
The inside [] statement builds a list of all required values not in your map keys if the list is empty it evaluates to False, otherwise to True.
so if the map has not all required values, at least one element will be in the list built by the list comprehension expression. This will evaluate to True, so we negate the result to fulfill your code requirements (which are all required values should be present in the map)
Upvotes: 0