The Python Oracle

sort dict or list by second value of the tuple and then by the first one

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Melt

--

Chapters
00:00 Question
01:15 Accepted answer (Score 2)
01:53 Answer 2 (Score 0)
02:13 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)]