2

This has likely been asked before, but does anyone know of an elegant way to implement argmin in Python? That is, given a dictionary D mapping integers to integers, I want to find the key k such that D[k] is minimized.

For example:

d = {1: 100, 2:200}
argmin(d) = 1
Ryan
  • 7,621
  • 5
  • 18
  • 31

1 Answers1

7
def argmin(d):
    if not d: return None
    min_val = min(d.values())
    return [k for k in d if d[k] == min_val][0]

d = {1: 50, 2:100, 3:11}
min_index = argmin(d)

EDIT

min has an optional key parameter so you can use this instead:

min_index = min(d, key=d.get)
anthonybell
  • 5,790
  • 7
  • 42
  • 60
  • This is wrong and incredibly inefficient. It takes quadratic time, it uses `max` instead of `min`, and it uses `is` where it should use `==`. – user2357112 May 07 '15 at 04:21
  • I'm not saying it can't be improved. But how come it uses quadratic time? As I see it it is linear. – spalac24 May 07 '15 at 04:45
  • @user3267581: The original version calculated `min(z.values())` for every key. – user2357112 May 07 '15 at 05:14
  • Yeah, I did a `%timeit` in ipython and it was dramatically slower if you use `min(z.values())` in the list comprehension. – anthonybell May 07 '15 at 05:24