Define key in nlargest() of heapq?

Raymond Hettinger python at rcn.com
Mon Nov 12 22:33:07 EST 2007


On Nov 12, 6:56 pm, Davy <zhushe... at gmail.com> wrote:
> I have a dictionary with n elements, and I want to get the m(m<=n)
> keys with the largest values.
>
> For example, I have dic that includes n=4 elements, I want m=2 keys
> have the largest values)
> dic = {0:4,3:1,5:2,7:8}
> So, the the largest values are [8,4], so the keys are [7,0].
>
> How to do this by nlargest() of heapq? I have tried
> nlargest(2,dic,key),

Try this:

>>> from heapq import nlargest
>>> dic = {0:4,3:1,5:2,7:8}
>>> from operator import itemgetter
>>> nlargest(2, dic, dic.__getitem__)
[7, 0]


Raymond




More information about the Python-list mailing list