Python: sorting the values of a dict and extracting the keys corresponding to the last n values -


say have dict this, not ordered in values:

d={a:2,k:2,c:11,f:17,e:84,y:86}

and want sort values largest smallest:

order=sorted(d.values(),reverse=true)

this give you:

order=[86,84,17,11,2,2]

now, let's take last 2 elements:

b=order[-2:]=[2,2]

what pythonic way of retrieving keys in d values in b correspond? in case, intended outcome be:

ans=[a,k]

use key argument sorted():

>>> d = {"a":2, "k":2, "c":11, "f":17, "e":84, "y":86} >>> sorted(d, key=d.get, reverse=true)[-2:] ['a', 'k'] 

from docs:

key specifies function of 1 argument used extract comparison key each list element: key=str.lower. default value none (compare elements directly).


Comments

Popular posts from this blog

php - How to add and update images or image url in Volusion using Volusion API -

javascript - jQuery UI Splitter/Resizable for unlimited amount of columns -

javascript - IE9 error '$'is not defined -