Skip to content
Advertisement

How to get a list of dictionaries sorted by three criteria

I want to get a list sorted accordingly to the following rules persons.sort(key = lambda p: (abs(p["height"] - 180), p["weight"]==75, p["weight"])) i.e. I need it to get sorted firstly by its closeness to the height 180, then all of the weight values which are equal to 75, and then I want them to be sorted ascendingly by its weight…

I came up with the following code, which is not working…

def get_ordered_list(persons):
    persons.sort(key = lambda p: p["name"] )
    persons.sort(key = lambda p: (abs(p["height"] - 180), p["weight"]==75, p["weight"]))
    return persons

For the following sample data, for instance,

array = [{"name": "Guido Batista", "height": 195, "weight": 110},
    {"name":"Heitor Tostes", "height": 180, "weight": 75},
    {"name":"Bruno Costa", "height": 180, "weight": 75},
    {"name":"Joao Kleber", "height": 180, "weight": 65},
    {"name":"Rafael Rodrigues", "height": 165, "weight": 110},
    {"name":"Ricardo Neto", "height": 170, "weight": 70},
    {"name":"Juca Carvalho", "height": 180, "weight": 77}]
    

I need to get the list sorted as such:

[
      {"name":"Bruno Costa", "height": 180, "weight": 75},
      {"name":"Heitor Tostes", "height": 180 , "weight": 75},
      {"name":"Joao Kleber", "height": 180, "weight": 65},
      {"name":"Juca Carvalho", "height": 180, "weight": 77},
      {"name":"Ricardo Neto", "height": 170, "weight": 70},
      {"name": "Guido Batista", "height": 195, "weight": 110},
      {"name":"Rafael Rodrigues", "height": 165, "weight": 110},
]

Advertisement

Answer

This is happening because False is a lower value than True. Use

 persons.sort(key = lambda p: (abs(p["height"] - 180), p["weight"]!=75, p["weight"]))

changing the comparison for the “weight” key.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement