-3

I have a list of python dicts like this:

[{'name': 'A', 'score': 12}, 
{'name': 'B', 'score': 20},
{'name': 'C', 'score': 11},
{'name': 'D', 'score': 20},
{'name': 'E', 'score': 9}]

How do I select first three dicts with highest score values? [D, B, A]

PaCi
  • 143
  • 1
  • 1
  • 7
  • By "most score values", do you mean "highest score"? – jarmod Jun 19 '20 at 15:18
  • 1
    Sort it by score, slice the result. – deceze Jun 19 '20 at 15:18
  • Yes, highest score – PaCi Jun 19 '20 at 15:19
  • Sort like `mylist.sort(key=lambda x:x["score"],reverse=True)` - and as for the slice, it depends what you mean by "most". – alani Jun 19 '20 at 15:19
  • 1. Sort it by score in descending order then slice the first 3; or 2. Sort it by score in ascending order then slice the last 3 – Ronie Martinez Jun 19 '20 at 15:20
  • The above is an in-place sort. If you want to return the sorted copy then use `sorted` instead, and use `key` and `reverse` arguments similarly. – alani Jun 19 '20 at 15:21
  • @RonieMartinez Question implied descending order. – alani Jun 19 '20 at 15:22
  • Question also wants just the `name` elements... `[d['name'] for d in sorted(mylist, key=lambda x:x["score"],reverse=True)[:3]]` should do it (not tested). – alani Jun 19 '20 at 15:24
  • try `.sort(key=lambda x: x['score'], reverse=True)` on the list, this will sort the list by the score – Chase Jun 19 '20 at 15:27
  • Well that _almost_ got the OP's example output except that it's a stable sort and they wanted the equal elements in reversed order... So I guess we go with the following version: `[d['name'] for d in list(reversed(sorted(mylist, key=lambda x:x["score"])))[:3]]` Gives `['D', 'B', 'A']` – alani Jun 19 '20 at 15:27

1 Answers1

0

Sort using the score as a key, then take the top 3 elements:

>>> sorted([{'name': 'A', 'score': 12},
...     {'name': 'B', 'score': 20},
...     {'name': 'C', 'score': 11},
...     {'name': 'D', 'score': 20},
...     {'name': 'E', 'score': 9}], key=lambda d: d['score'])[-3:]
[{'name': 'A', 'score': 12}, {'name': 'B', 'score': 20}, {'name': 'D', 'score': 20}]
Samwise
  • 68,105
  • 3
  • 30
  • 44