return key of minimum value
Question:
I want to return the key of the minimum value in a dictionary
in Python. The value of key, value pair will have several numbers, i.e. dict[current] = (total, gone, heuristic)
. How can I return the key of minimum gone value?
Answers:
you can iterate through the dictionary
best = None
for key, t in d.items():
if best is None or t[1] < d[best][1]:
best = key
return best
Use min
with a lambda lookup function:
min(d, key=lambda k: d[k][1])
Simply, iterate through the dictionary:
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
I want to return the key of the minimum value in a dictionary
in Python. The value of key, value pair will have several numbers, i.e. dict[current] = (total, gone, heuristic)
. How can I return the key of minimum gone value?
you can iterate through the dictionary
best = None
for key, t in d.items():
if best is None or t[1] < d[best][1]:
best = key
return best
Use min
with a lambda lookup function:
min(d, key=lambda k: d[k][1])
Simply, iterate through the dictionary:
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