How to get a set of keys with largest values?

DouhetSukd DouhetSukd at gmail.com
Tue Nov 13 03:42:52 EST 2007


On Nov 12, 1:07 am, Davy <zhushe... at gmail.com> wrote:
> Hi all,
>
> I have a dictionary with n elements, and I want to get the m(m<=n)
> keys with the largest values.
>
> For example, I have dic that includes n=4 elements, I want m=2 keys
> have the largest values)
> dic = {0:4,3:1,5:2,7:8}
> So, the the largest values are [8,4], so the keys are [7,0].
>
> Is there any fast way to implement this algorithm?
> Any suggestions are welcome!
>
> Best regards,
> Davy

#get a list of tuples, with value in 1st position, key second
li = [(value,key) for key, value in dic.items()]

#sort the list
li.sort()

m = 2
#grab the m highest values, from the end of the list
li_high_keys = [k for v, k in li[-m:]]




More information about the Python-list mailing list