-1

I have this dictionary:

dic_kol={"History :":2,"Horror :": 2 ,"Adventure :":1 ,"Comedy :":2 ,"Romance :":2 ,"Action :":3}

Now I want sort dictionary by order of values and if two values was same then sort alphabetically. But required sort numerically ascending and alphabetic descending.

For example in this example output must be:

[('Action :', 3), ('Comedy :', 2), ('History :', 2), ('Horror :', 2), ('Romance :', 2), ('Adventure :', 1)]

But my code is:

print(sorted(dic_kol.items(),key=lambda x: (x[1],x[0]),reverse=True))

And my output is:

[('Action :', 3), ('Romance :', 2), ('Horror :', 2), ('History :', 2), ('Comedy :', 2), ('Adventure :', 1)]
borchvm
  • 3,533
  • 16
  • 44
  • 45
  • Does this answer your question? [How do I sort a dictionary by value?](https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value) – Roshin Raphel Mar 05 '23 at 10:54

1 Answers1

0

reverse=True reverses both the numeric and the alphabetical comparisons! but you only want to reverse the numerical comparisons, not the alphabetical comparisons.

Here are two possible ways to do that:

  • Sort twice, sorting by the tie-breaker first, and by the main criterion second, taking advantage of the stability of the sort, setting reverse=True only for the second sort:
print(sorted(sorted(dic_kol.items(),key=lambda x: x[0]), key=lambda x: x[1], reverse=True))
  • Sort once, reversing the numerical values by multiplying them by -1
print(sorted(dic_kol.items(),key=lambda x: (-x[1],x[0])))
Stef
  • 13,242
  • 2
  • 17
  • 28