I need to get all keys in a dictionary whose corresponding value is above a minimum and that are in a given list. Something like:
result = [k for k in my_dict if my_dict[k] > min_value and k in allowed_keys]
However, it may be the case that I have no restriction on allowed keys. I find that the most pythonic to do it is to set allowed_keys to None. But this would leave me with the ugly piece of code:
if allowed_keys is None:
result = [k for k in my_dict if my_dict[k] > min_value]
else:
result = [k for k in my_dict if my_dict[k] > min_value and k in allowed_keys]
I feel like there must be a more sensible and pythonic solution. I thought of using a lambda function, but I’m not sure. Any ideas?
You should also follow good design principles (e.g. The Zen of Python) in addition to seeking the ‘most pythonic’ syntax for the solution.
Your code would be much clearer with the introduction of an
allow_all_keysboolean property rather than overloading the meaning ofallowed_keys. Doing this, the code then becomes:From The Zen of Python: