sorting nested dictionary

Max M maxm at mxm.dk
Wed Mar 13 04:27:21 EST 2002


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