2

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
2
  • 2
    That's not a valid dictionary, you can't have duplicate keys. Commented Dec 10, 2021 at 1:23
  • 1
    A standard trick is to return math.inf for the values you want to ignore when taking the minimum. Likewise use -math.inf for finding the maximum. So your example would be key=lambda k: math.inf if k in my_set else my_dict[k] Commented Dec 10, 2021 at 1:27

3 Answers 3

5

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])
Sign up to request clarification or add additional context in comments.

3 Comments

No point building a dict with values, as min is going to ignore them.
You're right, we just need a list of keys.
Since you posted that answer, I won't bother editing mine.
1

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.)

Comments

1

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])

2 Comments

Putting extra effort into the values that min is going to ignore anyway seems wasteful.
@KellyBundy you're right, that's an excellent point. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.