0

I have a list of dictionary like below,

x = [
   {"matches_count": 10, distance: 50},
   {"matches_count": 20, distance: 50},
   {"matches_count": 1, "distance: 20},
   {"matches_count": 2, "distance": 20},
   {"matches_count": 5, "distance: 30},
]

I need to sort this like below

x = [
  {"matches_count": 2, distance: 20},
  {"matches_count": 1, "distance: 20},
  {"matches_count": 5, "distance: 30},
  {"matches_count": 20, distance: 50},
  {"matches_count": 10, "distance": 50} 
]

Basically, this should be sort with both distance and the matches_count. When the distance is the same the highest matches count should come first. Is there any possibility to do this with the sorted method? Or is there any other way to perform this?

I have checked the below questions and I did not able to get proper insight from them for my question. Sort list of dictionaries by multiple keys with different ordering

Theesh
  • 187
  • 1
  • 18
  • Does this answer your question? [How do I sort a list of dictionaries by a value of the dictionary?](https://stackoverflow.com/questions/72899/how-do-i-sort-a-list-of-dictionaries-by-a-value-of-the-dictionary) and [Sort list of lists ascending and then descending](https://stackoverflow.com/q/6666748/4518341) – wjandrea Jul 16 '21 at 03:32

3 Answers3

2

You can just sort by a key, where the key is a tuple and you flip the sign of matches count. This will sort first by distance ascending, then matches descending.

x.sort(key=lambda e: (e["distance"], -e["matches_count"]))
Exalted Toast
  • 656
  • 5
  • 12
1

You could use the sorted function:

print(sorted(x, key=lambda a: (a['distance'], -a['matches_count'])))

Output:

[{'matches_count': 2, 'distance': 20}, {'matches_count': 1, 'distance': 20}, {'matches_count': 5, 'distance': 30}, {'matches_count': 20, 'distance': 50}, {'matches_count': 10, 'distance': 50}]

This sorts by first the distance key, and if it's the same, it sorts by the negative of the matches_count. I make it negative so it sorts in a descending order instead of an ascending order.

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
1
x = [
    {"matches_count": 10, "distance": 50},
    {"matches_count": 20, "distance": 50},
    {"matches_count": 1, "distance": 20},
    {"matches_count": 2, "distance": 20},
    {"matches_count": 5, "distance": 30},
]

x.sort(key=lambda k: (k['distance'], -k['matches_count']))

for e in x:
    print(e)
nononohup
  • 111
  • 5