Order by value in dictionary

Duncan Booth duncan.booth at invalid.invalid
Thu Oct 18 05:40:33 EDT 2007


Marc 'BlackJack' Rintsch <bj_666 at gmx.net> wrote:

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

Isn't that just equivalent to:

def sortt(d):
    return sorted(d.iterkeys(), key=d.__getitem__,
                 reverse=True)

which has the advantage of not building a list of tuples just to throw it 
away?



More information about the Python-list mailing list