I have a dictionary with values mapping some object to an integer; e.g. {node: 1, node: 2}.
I want to get the key that corresponds to the minimum value in this dictionary, which I know I can do with:
min_key = min(my_dict, key=lambda k: my_dict[k])
However, I'd also like to add the constraint that the key is not contained within some other set. Here's the pseudo-code that I wished worked:
min_key = min(my_dict, key=lambda k: my_dict[k] where k not in my_set)
Is there a way to write this as a one-liner in python as part of a lambda, or do I now have to explicitly loop through the dictionary and add the logic within the loop like this?
min_key, min_value = None, float('inf')
for k,v in my_dict.items():
if v < min_value and k not in my_set:
min_key = k
return min_key
math.inffor the values you want to ignore when taking the minimum. Likewise use-math.inffor finding the maximum. So your example would bekey=lambda k: math.inf if k in my_set else my_dict[k]