sorting nested dictionary

Max M maxm at mxm.dk
Wed Mar 13 16:08:49 EST 2002


dsavitsk wrote:

> thanks.  the following solution was also sent, seems to work, but i don't
> know why ...

> def compare(a, b):
>     return cmp(a[1]['weighted'], b[1]['weighted'])
> 
> pairs = h['ids'].items()
> pairs.sort(compare)

the "cmp()" function is the key here:

cmp(x, y)
Compare the two objects x and y and return an integer according to the 
outcome. The return value is negative if x < y, zero if x == y and 
strictly positive if x > y.

----------------------------

And yes that is the 'correct' way of doing it, but the tuple way is 
faster. get it from the horses mouth below.

regards Max M

----------------------------

Sorting
 From Guido van Rossum

Sorting lists of basic Python objects is generally pretty efficient. The 
sort method for lists takes an optional comparison function as an 
argument that can be used to change the sorting behavior. This is quite 
convenient, though it can really slow down your sorts.

An alternative way to speed up sorts is to construct a list of tuples 
whose first element is a sort key that will sort properly using the 
default comparison, and whose second element is the original list element.

Suppose, for example, you have a list of tuples that you want to sort by 
the n-th field of each tuple. The following function will do that.

def sortby(list, n):
     nlist = map(lambda x, n=n: (x[n], x), list)
     nlist.sort()
     return map(lambda (key, x): x, nlist)

Here's an example use:
 >>> list = [(1, 2, 'def'), (2, -4, 'ghi'), (3, 6, 'abc')]
 >>> list.sort()
 >>> list
[(1, 2, 'def'), (2, -4, 'ghi'), (3, 6, 'abc')]
 >>> sortby(list, 2)
[(3, 6, 'abc'), (1, 2, 'def'), (2, -4, 'ghi')]
 >>> sortby(list, 1)
[(2, -4, 'ghi'), (1, 2, 'def'), (3, 6, 'abc')]




More information about the Python-list mailing list