sorting two corresponding lists?

Piet van Oostrum piet at cs.uu.nl
Thu Apr 23 08:57:01 EDT 2009


>>>>> Saketh <saketh.bhamidipati at gmail.com> (S) wrote:

>S> Why not use a dictionary instead of two lists? Then you can sort the
>S> dictionary by value -- e.g.

>S> d = dict(zip(items, values))
>S> sorted_items = sorted(d.iteritems(), key=lambda (k,v): (v,k))

>S> This produces a list of pairs, but demonstrates the general idea.

This will fail if there are duplicates in the items. And if we assume no
duplicates the key doesn't need the k part:

sorted_items = sorted(d.iteritems(), key=lambda (k,v): v)

or

from operator import itemgetter
sorted_items = sorted(d.iteritems(), key=itemgetter(1))

-- 
Piet van Oostrum <piet at cs.uu.nl>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org



More information about the Python-list mailing list