在字典中找到最小非零值(Python)

Kon*_* K. 2 python dictionary min python-3.x

我有一本字典,我想获得其值为最小非零值的密钥.

例如给出输入:

{1:0, 2:1, 3:2}
Run Code Online (Sandbox Code Playgroud)

它将返回2.

Mao*_*eli 5

你可以在一次迭代中完成.

d = {1:0, 2:1, 3:2}

# Save the minimum value and the key that belongs to it as we go
min_val = None
result = None
for k, v in d.items():
    if v and (min_val is None or v < min_val):
        min_val = v
        result = k

print(result)
Run Code Online (Sandbox Code Playgroud)

一些假设:

  • 将考虑负值
  • 它将返回找到的第一个键
  • 如果有帮助,min_val将保持最小值