-1

I have a dictionary and a set. I want to return the key associated with the minimum value if that key is not already in the set without creating a second dictionary used to delete items that are already in the set.

Example: I have dictionary

d = {1:10, 2:20, 3:30, 4:40}

and a set

s = set([1,2])

It should return 3

Mike Tibb
  • 91
  • 8
  • 3
    so make a dictionary that only contains the key:values that are not in the set and return the minimum of that, what is the issue. – Tadhg McDonald-Jensen Nov 18 '16 at 02:25
  • I did that I just wanted to know if there was another way to do it that did not involve making another dictionary. – Mike Tibb Nov 18 '16 at 02:29
  • Apart from having to construct/filter for keys not in s, this is a **near-duplicate of [Get key with the least value from a dictionary](http://stackoverflow.com/questions/3282823/get-key-with-the-least-value-from-a-dictionary)** – smci Nov 18 '16 at 02:32
  • I had seen that question but the added filter was the part I was asking for help on. – Mike Tibb Nov 18 '16 at 02:41

3 Answers3

2

Use the set operations to subtract the set s from the set of keys of d, then use min with key=d.get to get the remaining key with the smallest value:

d = {1:10, 2:20, 3:30, 4:40}
s = set([1,2])

print min(set(d) - s, key=d.get)

prints 3

If the result must be None when no key was found use:

q = set(d) - s
print min(q, key=d.get) if q else None

Rather than the ValueError from min.

Dan D.
  • 73,243
  • 15
  • 104
  • 123
1

You could use min with generator expression that returns keys not in s and key parameter that gets the value from d:

>>> d = {1:10, 2:20, 3:30, 4:40}
>>> s = set([1,2])
>>> min((k for k in d if k not in s), key=d.get)
3

Above approach wouldn't create any intermediate containers. In case there's a possibility that s matches keys from d default value can be used:

>>> d = {1:10, 2:20, 3:30, 4:40}
>>> s = set([1,2,3,4])
>>> min((k for k in d if k not in s), key=d.get, default=-1)
-1
niemmi
  • 17,113
  • 7
  • 35
  • 42
1

Set operations work nicely here.

d = {1:10, 2:20, 3:30, 4:40}
s = set([1,2])

def find_min(d, s):
    keys = set(d)
    difference = keys-s
    return min(difference) if difference else None

>>> print find_min(d, s)
3

alternatively, you could have difference = filter(lambda e: e not in s, d)

ospahiu
  • 3,465
  • 2
  • 13
  • 24