返回最小值的密钥



我想在 Python 中返回dictionary中最小值的键。键的值,值对将有几个数字,即dict[current] = (total, gone, heuristic).如何返回最小消失值的密钥?

min与 lambda 查找函数一起使用:

min(d, key=lambda k: d[k][1])

简单地说,遍历字典:

d = {1: (1,2,3), 2: (2,4,5), 4: (5,0,2)}
best = None
mn = 99999999 # if you have values more than this, then use float('inf') instead
for k in d:
if mn > d[k][1]:
mn = d[k][1]
best = k 
print(best)
# Output: 4

您可以遍历字典

best = None
for key, t in d.items():
if best is None or t[1] < d[best][1]:
best = key
return best

最新更新