-3

I have an array object like that, Not sort value, I want descending order and just 3 objects has a high value:

[{'id': 1, 'value': 3}, 
{'id': 2, 'value': 6},
{'id': 3, 'value': 8}, 
{'id': 4, 'value': 8}, 
{'id': 5, 'value': 10},
{'id': 6, 'value': 9},
{'id': 7, 'value': 8},
{'id': 8, 'value': 4},
{'id': 9, 'value': 5}]

I want result is descending order and just 3 objects have a high value, like this

[{'id': 5, 'value': 10},
{'id': 6, 'value': 9},
{'id': 7, 'value': 8},
{'id': 3, 'value': 8}, 
{'id': 4, 'value': 8},]

Please help me, thanks

Beginer
  • 365
  • 4
  • 12
  • Please take some time to refresh [the help pages](http://stackoverflow.com/help), take the SO [tour], read [ask], as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). Then [edit] your question to include a [mre] of your own attempt, together with a description of the problems you have with it. – Some programmer dude Aug 12 '22 at 06:27
  • `obj.sort( key = lambda k: -k['value'])`. Just do a normal sort, specifying the key you want. Making it negative will sort in descending order. – Tim Roberts Aug 12 '22 at 06:30
  • Not sort value, I want descending order and just 3 objects has a high value – Beginer Aug 12 '22 at 06:35

1 Answers1

-1
t = [{'id': 1, 'value': 3}, 
{'id': 2, 'value': 6},
{'id': 3, 'value': 8}, 
{'id': 4, 'value': 8}, 
{'id': 5, 'value': 10},
{'id': 6, 'value': 9},
{'id': 7, 'value': 8}]

newlist = sorted(t, key=lambda d: d['value'])
newlist.reverse()
print(newlist[:3])
# [{'id': 5, 'value': 10}, {'id': 6, 'value': 9}, {'id': 7, 'value': 8}]

More info about list slicing

More info about reverse()

More info

TheTS
  • 142
  • 8