sorting nested dictionary

dsavitsk dsavitsk at e-coli.net
Wed Mar 13 15:50:16 EST 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)

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

"Max M" <maxm at mxm.dk> wrote in message news:3C8F1B79.8000607 at mxm.dk...
> dsavitsk wrote:
>
>
> > i would like to sort this portion by 'weighted'.  is there a quick (as
in
> > programming time, not sorting time) better way to do this other than
dumping
> > the values to a list, sorting, and realigning the data?  that seems so
> > unpythonic to me somehow.
>
> How do you mean "sort" a dictionary? A dictionary will allways return
> the items in a random order.
>
> What you mean is probably that you want a list of keys that are sorted
> according to the value of weighted?
>
> Then you just create a list of tuples with the values you want to sort
> on first, and the key in the end of the tuple. This list you sort with
> the built in 'sort()'
>
> untested:
>
> dict = {'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},}}
>
> sortedList = []
> for key, val in dict['ids'].items():
>      sortedList.append((val['weighted'],key))
> sortedList.sort()
> sortedKeys = [item[1] for item in sortedList]
>
> regards Max M
>





More information about the Python-list mailing list