Order by value in dictionary

Peter Otten __peter__ at web.de
Wed Oct 17 11:44:39 EDT 2007


Abandoned wrote:

> These are some method..
> Now the fastest method is second..

Your four functions return three different results for the same input.
First make sure it's correct, then make it faster (if necessary).

Here are two candidates:

def largest_sort(d, n):
    return sorted(d, key=d.__getitem__, reverse=True)[:n]

def largest_heap(d, n):
    return heapq.nlargest(n, d, d.__getitem__)

Peter



More information about the Python-list mailing list