Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]

like image 323
FaCoffee Avatar asked Dec 10 '22 14:12

FaCoffee


1 Answers

Use the key argument to sorted() to get a list of keys sorted by values:

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

To quote the documentation:

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

Alternatively, (if n is small) you can use heapq.nsmallest, which avoids sorting all the keys:

>>> from heapq import nsmallest
>>> nsmallest(2, d, key=d.get)
['a', 'k']
like image 160
Eugene Yarmash Avatar answered Jan 11 '23 23:01

Eugene Yarmash