sorting nested dictionary

Gustavo Cordova gcordova at hebmex.com
Wed Mar 13 22:01:11 CET 2002


> 
> thanks.  the following solution was also sent, seems to work, 
> but i don't know why ...
> 
> ---------------------------------------------------------
> from pprint import pprint
> h = {'ids': {'2778xxxxx': {'weighted': 4.6, 'raw': 5.0},
>              '3059xxxxx': {'weighted': 6.1, 'raw': 6.0},
>              '3188xxxxx': {'weighted': 3.2, 'raw': 4.0},
>              '3216xxxxx': {'weighted': 10.1, 'raw': 7.0},
>              '3257xxxxx': {'weighted': 9.7, 'raw': 9.0},
>              '3266xxxxx': {'weighted': 4.8, 'raw': 3.0},}}
> 
> def compare(a, b):
>     return cmp(a[1]['weighted'], b[1]['weighted'])
> 
> pairs = h['ids'].items()
> pairs.sort(compare)
> 
> pprint (pairs)
> 
> ----------------------------------------------------------

It works because....

>>> pairs = h['ids'].items()

Now, "pairs" contains a list of tuples, in the form:

pairs = [
	( '2778xxxxx', {'weighted': 4.6, 'raw': 5.0} ),
	( '3059xxxxx', {'weighted': 6.1, 'raw': 6.0} ),
	( '3188xxxxx', {'weighted': 3.2, 'raw': 4.0} ),
	( '3216xxxxx', {'weighted': 10.1, 'raw': 7.0} ),
	( '3257xxxxx', {'weighted': 9.7, 'raw': 9.0} ),
	( '3266xxxxx', {'weighted': 4.8, 'raw': 3.0} ) ]

The expression "a[1]['weighted']" returns tne value of the
item "weighted" of the second element of a tuple, so the function

def compare(a,b):
	return cmp(a[1]['weighted'],b[1]['weighted'])

returns the comparison of the "weighted" sub-element of tuples a and b.
So now, you simple sort the list, specifying this function as the
comparison function to use:

pairs.sort(compare)

ta-daa.

Ain't Python the best?

damn...

so powerful, and so easy to understand.

-gustavo




More information about the Python-list mailing list