FaCoffee
FaCoffee

Reputation: 7929

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]

Upvotes: 4

Views: 3500

Answers (3)

Eugene Yarmash
Eugene Yarmash

Reputation: 149991

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']

Upvotes: 12

MMF
MMF

Reputation: 5921

Here is another method using np.argsort :

d.values()
# returns [2, 11, 84, 17, 2, 86]

np.argsort(d.values())
# array([0, 4, 1, 3, 2, 5]). 
# Returns the indices that would sort an array.

# Now use it to retrieve the corresponding keys :
for i in np.argsort(d.values())[:2]:
    print d.keys()[i]

Result:

'a'
'k'

Upvotes: 2

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48090

If you want key and values both after sorting the dict, you may do:

>>> from operator import itemgetter
>>> order = sorted(d.items(), key=itemgetter(1), reverse=True)
>>> order[-2:]
[('a', 2), ('k', 2)]

Upvotes: 1

Related Questions