Alignment of dictionaries in Python list

Asked 2 years ago, Updated 2 years ago, 15 views

That

a=[{'apple'=30,'banana'=50,'fruit'=25},
   {'apple'=50'banana'=30,'fruit'=10},
   {'apple'=22,'banana'=55,'fruit'=66},
   {'apple'=32,'banana'=10,'fruit'=5}]

There is a dictionary on the list like this, and I want to know the ranking by fruit, so what should I do?

I want to do 66 with a high number of fruit, accept the number 1 for the first time, accept 2 for 25, accept 3 for 10, and accept 4 for 5, but it's not easy to use the rank function or max function.

python

2022-09-20 21:59

1 Answers

sorted(a, key=lambdad:(d['fruit'], d['apple'], reverse=True) # if fruit is the same as apple

[{'apple': 22, 'banana': 55, 'fruit': 66},
 {'apple': 30, 'banana': 50, 'fruit': 25},
 {'apple': 50, 'banana': 30, 'fruit': 10},
 {'apple': 32, 'banana': 10, 'fruit': 5}]


2022-09-20 21:59

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.