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?
Asked
Active
Viewed 301 times
2
-
1Does this answer your question? [Get the key corresponding to the minimum value within a dictionary](https://stackoverflow.com/questions/3282823/get-the-key-corresponding-to-the-minimum-value-within-a-dictionary) – Stuart Feb 09 '20 at 06:07
3 Answers
0
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

mattyx17
- 806
- 6
- 11
-
-
-
1
-
-
Sorry had a typo. Basically `best` keeps track of the best key seen. Then for each tuple compare its gone value (the value at index 1) to the gone value of the best and if it is better then update `best` – mattyx17 Oct 19 '22 at 13:57
0
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

LordOfThunder
- 310
- 1
- 3
- 17