Roger
Roger

Reputation: 93

Getting second and third highest value in a dictionary

dict = {'a':5 , 'b':4, 'c':3, 'd':3, 'e':1}

Second is 'b' with 4 times. Joint third are 'c' and 'd' with 3 times. As the dictionary changes over time, say, 'f' is added with a value of 3, then third will be 'c', 'd', and 'f' with 3 times.

Upvotes: 2

Views: 7700

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140168

just create a gencomp of tuple value,key and sort it. Print items

d = {'a':5 , 'b':4, 'c':3, 'd':3, 'e':1}

x = sorted(((v,k) for k,v in d.items()))
print(x[-2][1])
print(x[-3][1])

result:

b
d

(would fail if dict doesn't have at least 3 items)

Or directly with key parameter (avoids data reordering)

x = sorted(d.items(),key=(lambda i: i[1]))
print(x[-2][0])
print(x[-3][0])

result:

b
d

BTW avoid using dict as a variable.

EDIT: since there are several identical values, you may want to get the 2 second best values and the associated letters. You have to do it differently. I'd create a default list using key as value and store in a list, then sort it as done in the above code:

import collections

d = {'a':5 , 'b':4, 'c':3, 'd':3, 'e':1}

dd = collections.defaultdict(list)

for k,v in d.items():
    dd[v].append(k)

x = sorted(dd.items())

print(x[-2])
print(x[-3])

result:

(4, ['b'])
(3, ['c', 'd'])

Upvotes: 6

Related Questions