Order by value in dictionary

Amit Khemka khemkaamit at gmail.com
Thu Oct 18 07:54:08 EDT 2007


On 10/17/07, Abandoned <besturk at gmail.com> wrote:
> Very very thanks everbody..
>
> These are some method..
> Now the fastest method is second..
>
> ==== 1 ===
> def sortt(d):
>     items=d.items()
>     backitems=[ [v[1],v[0]] for v in items]
>     backitems.sort()
>     #boyut=len(backitems)
>     #backitems=backitems[boyut-500:]
>     a=[ backitems[i][1] for i in range(0,len(backitems))]
>     a.reverse()
>     return a
>
> ==== 2 =====
> import operator
> def sortt(d):
>     backitems=d.items()
>     boyut=len(backitems)
>     backitems=backitems[boyut-500:]
>     backitems=sorted(backitems, key=operator.itemgetter(1))
>     a=[ backitems[i][0] for i in range(0,len(backitems))]
>     a.reverse()
>     return a
>
> ==== 3 =====
> def sortt(d):
>     backitems=d.items()
>     backitems.sort(lambda x,y:cmp(x[1],y[1]))
>     backitems=sorted(backitems, key=operator.itemgetter(1))
>     a=[ backitems[i][0] for i in range(0,len(backitems))]
>     a.reverse()
>     return a
>
> ====== 4 =======
> import heapq
>
> def sortt(d):
>     backitems=d.items()
>     backitems=heapq.nlargest(1000, backitems, operator.itemgetter(1))
>     a=[ backitems[i][0] for i in range(0,len(backitems))]
>     a.reverse()
>     return a
>

Btw, there are specialized algorithms called "Selection Algorithms"
for finding k largest items in a collection.

http://en.wikipedia.org/wiki/Selection_algorithm

Cheers,
-- 
--
Amit Khemka



More information about the Python-list mailing list