sort dict or list by second value of the tuple and then by the first one
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Over a Mysterious Island Looping
--
Chapters
00:00 Sort Dict Or List By Second Value Of The Tuple And Then By The First One
00:59 Answer 1 Score 0
01:14 Accepted Answer Score 2
01:44 Thank you
--
Full question
https://stackoverflow.com/questions/6291...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python
#avk47
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Over a Mysterious Island Looping
--
Chapters
00:00 Sort Dict Or List By Second Value Of The Tuple And Then By The First One
00:59 Answer 1 Score 0
01:14 Accepted Answer Score 2
01:44 Thank you
--
Full question
https://stackoverflow.com/questions/6291...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python
#avk47
ACCEPTED ANSWER
Score 2
You could do something as follows:
output = sorted(l, key=lambda x: (x[1], [-ord(letter) for letter in x[0]]), reverse=True)
output will contain the following:
[('oo', 11), ('aa', 10), ('ee', 10)]
We are keeping the reverse order (descending), but we are passing a list as the second option (which are compared lexicographically by Python too) for sorting which will have the negative ASCII values for each letter. This way, -ord('a') (-97) is greater than -ord('e') (-101)
ANSWER 2
Score 0
I guess you should remove the reverse=True option, so that values would be sorted in the "right" order.
>>> l = [('ee',10), ('oo',11), ('aa', 10)]
>>> sorted(l, key=lambda k: (k[1], k[0]), reverse=False)
[('aa', 10), ('ee', 10), ('oo', 11)]