Order by value in dictionary

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Wed Oct 17 17:31:54 CEST 2007


On Wed, 17 Oct 2007 08:09:50 -0700, Abandoned wrote:

> Very very thanks everbody..
> 
> These are some method..
> Now the fastest method is second..

Maybe because the second seems to be the only one that's not processing
the whole dictionary but just 500 items less!?

You are building way too much intermediate lists in your functions.

> ==== 1 ===
> def sortt(d):
>     items=d.items()

Builds a list of all items.

>     backitems=[ [v[1],v[0]] for v in items]

Builds another list from all items.

>     backitems.sort()
>     a=[ backitems[i][1] for i in range(0,len(backitems))]

And again a new list *plus* a list of len(backitems) integers that is
built just to iterate over it.  Instead of iterating directly over
`backitems` without the index.

>     a.reverse()
>     return a

This whole function can be written as (untested):

def sortt(d):
    sorted_items = sorted((item[1], item[0]) for item in d.iteritems(),
                          reverse=True)
    return map(operator.itemgetter(1), sorted_items)

> ==== 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

Without throwing away 500 items:

def sortt(d):
    sorted_items = sorted(d.iteritems(),
                          key=operator.itemgetter(1),
                          reverse=True)
    return map(operator.itemgetter(0), sorted_items)

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list