Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting by nested dictionary in Python dictionary

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)
like image 276
SpanishBoy Avatar asked Aug 19 '15 14:08

SpanishBoy


3 Answers

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)
like image 145
Eli Korvigo Avatar answered Oct 06 '22 21:10

Eli Korvigo


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}]}
like image 31
Padraic Cunningham Avatar answered Oct 06 '22 23:10

Padraic Cunningham


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)
like image 2
CasualDemon Avatar answered Oct 06 '22 21:10

CasualDemon