-1

So basically I have a list of dictionaries with the following values :

[
 {'First Name ':'Stephen', 'Last Name':'Queen','Age':61,'Marks':89},
 {'First Name ':'Stephen', 'Last Name':'Queen','Age':89,'Marks':68},
 {'First Name ':'Angelica', 'Last Name':'King','Age':39,'Marks':84},
 {'First Name ':'Stephen', 'Last Name':'King','Age':29,'Marks':78},
 {'First Name ':'Stephen', 'Last Name':'Queen','Age':61,'Marks':84},
]

So I basically want to sort the values First in 'Ascending order' on First Name, then in 'Ascending order' on Second Name, then 'Descending order' on Age and finally 'Descending order'on marks. So, after sorting it should look like this :

[
 {'First Name ':'Angelica', 'Last Name':'King','Age':39,'Marks':84},
 {'First Name ':'Stephen', 'Last Name':'King','Age':29,'Marks':78},
 {'First Name ':'Stephen', 'Last Name':'Queen','Age':89,'Marks':68},
 {'First Name ':'Stephen', 'Last Name':'Queen','Age':61,'Marks':98},
 {'First Name ':'Stephen', 'Last Name':'Queen','Age':61,'Marks':89}
]

So my question is to use a Pythonic way to do it effeciently. I tried Solutions mentioned here, but could not think of replicating it to my case, where I want custom order over multiple keys at the same time (i.e. to create a sort of mapper to sort the dictionaries in a user-defined manner).

Gambit1614
  • 8,547
  • 1
  • 25
  • 51

1 Answers1

14

This is straight forward as python by default sorts tuples/lists first according to first cell, then second etc... so expanding on the solution you link to:

newlist = sorted(list_to_be_sorted, key=lambda k: (k['First Name '],k['Last Name'],-k['Age'],-k['Marks']))

The - sign will trick the ascending sort to do descend on "Marks" and "Age".

kabanus
  • 24,623
  • 6
  • 41
  • 74