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?

Asked By: zzzz

||

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
Answered By: mattyx17

Use min with a lambda lookup function:

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

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
Answered By: LordOfThunder
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.