在 Python 中为字典实现 argmin

Rya*_*yan 2 python dictionary function

以前可能有人问过这个问题,但是有人知道在 Python 中实现 argmin 的优雅方法吗?也就是说,给定一个将整数映射到整数的字典 D,我想找到键 k 使得 D[k] 最小化。

例如:

d = {1: 100, 2:200}
argmin(d) = 1
Run Code Online (Sandbox Code Playgroud)

ant*_*ell 8

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)
Run Code Online (Sandbox Code Playgroud)

编辑

min有一个可选的关键参数,因此您可以使用它:

min_index = min(d, key=d.get)
Run Code Online (Sandbox Code Playgroud)