tags:

views:

264

answers:

3

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?

+7  A: 
all(value in some_map for value in required_values)
SilentGhost
beautiful thank you
UberJumper
you're welcome.
SilentGhost
Note: this will only work for lists composed only of hashable elements. Otherwise you will get a TypeError exception when executing "value in some_map"
Triptych
+2  A: 
return set(required_values).issubset(set(some_map.keys()))
Joe Koberg
turns out the dict key lookup with "in" (in the accepted answer) is far faster than retrieving the keys list and converting it to a set.
Joe Koberg
A: 

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)

dweeves