How to get a set of keys with largest values?
Duncan Booth
duncan.booth at invalid.invalid
Mon Nov 12 04:18:34 EST 2007
Davy <zhushenli at gmail.com> wrote:
> 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].
>
> Is there any fast way to implement this algorithm?
> Any suggestions are welcome!
>
Don't implement it: just use it.
>>> dic = {0:4,3:1,5:2,7:8}
>>> from heapq import nlargest
>>> nlargest(2, dic, key=dic.__getitem__)
[7, 0]
>>>
More information about the Python-list
mailing list