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]
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 isNone
(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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With