Home > Software engineering >  Adding additional logic to a lambda function to get the minimum value from a python dictionary
Adding additional logic to a lambda function to get the minimum value from a python dictionary

Time:12-10

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

CodePudding user response:

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

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

CodePudding user response:

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({ k: my_dict[k] for k in set(my_dict).difference(my_set)}, key = lambda k: my_dict[k])
  • Related