Skip to content Skip to sidebar Skip to footer

Finding The Dictionary Key With Max Value

How can I find the dictionary key with max value and when their is a tier, we will take the alphabetically first key a = {'f':3, 't':5, 'c':5} ma = max(a, key = a.get) This retur

Solution 1:

You have to include the key in the max key function. The problem is that you want the max value, but the min key. Since the values are numerical, it is easiest to negate them and call min:

a = {'f':3, 't':5, 'c':5}
min(a, key=lambda k: (-a[k], k))
# 'c'

Solution 2:

Maybe you can negate the number and get the minimum number, since it's gonna get the smallest character, like this:

ma = min(a.items(), key=lambda x: (-x[1], x[0]))[0]

And if you print it:

print(ma)

Is:

c

Solution 3:

I find a way to solve this problem at How do I sort a dictionary by value? utilizig the key parameter of sorted function.

a = {'f':3, 't':5, 'c':5}
a_sorted = dict(sorted(a.items(), key=lambda item: item[0]))
ma =  max(a_sorted, key = a_sorted.get)

Post a Comment for "Finding The Dictionary Key With Max Value"