Getting second and third highest value in a dictionary -
dict = {'a':5 , 'b':4, 'c':3, 'd':3, 'e':1}
second 'b' 4 times. joint third 'c' , 'd' 3 times. dictionary changes on time, say, 'f' added value of 3, third 'c', 'd', , 'f' 3 times.
just create gencomp of tuple value,key , sort it. print items
d = {'a':5 , 'b':4, 'c':3, 'd':3, 'e':1} x = sorted(((v,k) k,v in d.items())) print(x[-2][1]) print(x[-3][1])
result:
b d
(would fail if dict doesn't have @ least 3 items)
or directly 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
variable.
edit: since there several identical values, may want 2 second best values , associated letters. have differently. i'd create default list using key value , store in list, sort done in above code:
import collections d = {'a':5 , 'b':4, 'c':3, 'd':3, 'e':1} dd = collections.defaultdict(list) 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'])
Comments
Post a Comment