CF84 CF84 - 29 days ago 15
Python Question

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

Say you have a dict like this, but not necessarily ordered in its values:

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


And you want to sort the values largest to smallest:

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


This will give you:

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


Now, let's take the last two elements:

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


What is a Pythonic way of retrieving the keys in
d
to which the values in
b
correspond?
In this case, the intended outcome would be:

ans=[a,k]

Answer

Use the key argument to 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 the docs:

key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).