5

I have below structure

{
    'searchResult' : [{
            'resultType' : 'station',
            'ranking' : 0.5
        }, {
            'resultType' : 'station',
            'ranking' : 0.35
        }, {
            'resultType' : 'station',
            'ranking' : 0.40
        }
    ]
}

and want to get

{
    'searchResult' : [{
            'resultType' : 'station',
            'ranking' : 0.5
        }, {
            'resultType' : 'station',
            'ranking' : 0.4
        }, {
            'resultType' : 'station',
            'ranking' : 0.35
        }
    ]
}

Tried the code without success

result = sorted(result.items(), key=lambda k: k[1][0][1]["ranking"], reverse=True)
Maroun
  • 94,125
  • 30
  • 188
  • 241
SpanishBoy
  • 2,105
  • 6
  • 28
  • 51
  • Thanks all! But which method is faster `d["item"].sort()` or `sorted()`? – SpanishBoy Aug 19 '15 at 14:44
  • 1
    possible duplicate of [How do I sort a list of dictionaries by values of the dictionary in Python?](http://stackoverflow.com/questions/72899/how-do-i-sort-a-list-of-dictionaries-by-values-of-the-dictionary-in-python) – PyNEwbie Aug 19 '15 at 14:45
  • @SpanishBoy `sorted` returns a new object. If you don't need the original object you'd better stick with `sort` for speed and memory efficiency. – Eli Korvigo Aug 19 '15 at 14:47

3 Answers3

5

If you are okay with changing the objects in-place.

a = {
    'searchResult' : [{
                       'resultType' : 'station',
                       'ranking' : 0.5
                      }, {
                       'resultType' : 'station',
                       'ranking' : 0.35
                      }, {
                      'resultType' : 'station',
                      'ranking' : 0.40
                      }]
  }

a["searchResult"].sort(key=lambda d: d["ranking"], reverse=True)

Or you can make a deep copy to keep the original

from copy import deepcopy


srt_dict = deepcopy(a)
srt_dict["searchResult"].sort(key=lambda d: d["ranking"], reverse=True)
Eli Korvigo
  • 10,265
  • 6
  • 47
  • 73
5

You can simply do an inplace sort on the list, using key=itemgetter("ranking") and reverse=True:

from operator import itemgetter
d["searchResult"].sort(key=itemgetter("ranking"),reverse=True)

print(d)
{'searchResult': [{'resultType': 'station', 'ranking': 0.5}, {'resultType': 'station', 'ranking': 0.4}, {'resultType': 'station', 'ranking': 0.35}]}
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
2

You can just sort the list and write over itself in the dictionary.

result = {
    'searchResult' : [{
            'resultType' : 'station',
            'ranking' : 0.5
        }, {
            'resultType' : 'station',
            'ranking' : 0.35
        }, {
            'resultType' : 'station',
            'ranking' : 0.40
        }
    ]
}

result['searchResult'] = sorted(result['searchResult'], key= lambda x: x['ranking'], reverse=True)
CasualDemon
  • 5,790
  • 2
  • 21
  • 39