Adding additional logic to a lambda function to get the minimum value from a python dictionary

Viewed 54

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
3 Answers

Replace my_dict with a dictionary comprehension that returns the filtered dictionary.

min_key = min({k:v for k, v in my_dict.items() if k not in my_set}, 
                key = lambda k: my_dict[k])

It's similar to @Barmar's answer but you can also use set.difference between my_dict and my_set to filter the relevant dictionary:

out = min(set(my_dict).difference(my_set), key = lambda k: my_dict[k])

Just take the minimum over the filtered keys instead of all keys:

min_key = min(my_dict.keys() - my_set, key=my_dict.get)

(Note I also replaced your key function, no need to write your own.)

Related