Why this answer when there are already three other ones?
In my opinion none of the other answers exposed the core of the problem described in the question, which is by the way already sufficiently answered here: https://stackoverflow.com/questions/20145842/python-sorting-by-multiple-criteria and here https://stackoverflow.com/questions/55866762/how-to-sort-a-list-of-strings-in-reverse-order-without-using-reverse-true-parame
making it a candidate for becoming closed as a duplicate.
The feature of Python allowing to have a solution to the problem of sorting columns in different sorting orders is the fact that
Python’s sort is stable allowing you to use consecutive sorts, using the rightmost criteria first, then the next, etc. ( Martijn Pieters ).
That Python's sort algorithm is stable means that equal elements keep their relative order. So you can use a first sort on the second element (sorting in ascending order) and then sort again, on only the first element and in reverse order.
I have changed the dictionary listed in the question to having only string values what will not allow to use the 'trick' with negative number values in the key function to achieve the desired result to demonstrate what is said above.
The code below:
mydict = {
'Romance' : '2',
'Adventure' : '1',
'Action' : '3',
'Horror' : '2',
'History' : '2',
'Comedy' : '2',
}
mylist = list(mydict.items())
print(mylist)
print()
mylist = sorted(mylist)
print(mylist)
mslist = sorted(mylist, key=lambda x: (x[1]), reverse=True)
print(mslist)
from collections import OrderedDict
final = OrderedDict(mslist)
for key, value in final.items():
print(f' {key:10} : {value}')
creating following output:
[('Romance', '2'), ('Adventure', '1'), ('Action', '3'), ('Horror', '2'), ('History', '2'), ('Comedy', '2')]
[('Action', '3'), ('Adventure', '1'), ('Comedy', '2'), ('History', '2'), ('Horror', '2'), ('Romance', '2')]
[('Action', '3'), ('Comedy', '2'), ('History', '2'), ('Horror', '2'), ('Romance', '2'), ('Adventure', '1')]
Action : 3
Comedy : 2
History : 2
Horror : 2
Romance : 2
Adventure : 1
demonstrates what I am speaking about here.
From:
[('Action', '3'), ('Adventure', '1'), ('Comedy', '2'), ('History', '2'), ('Horror', '2'), ('Romance', '2')]
[('Action', '3'), ('Comedy', '2'), ('History', '2'), ('Horror', '2'), ('Romance', '2'), ('Adventure', '1')]
can be seen that the second sort moves only '('Adventure', '1')'
keeping the order of all the other items.