How to sort dictionary by decreasing integer value and then by decreasing string key?
Given dictionary,
test_dict = {"A" : 1, "B" : 3, "C" : 2, "D" : 3, "E" : 2}
I want to sort the items by decreasing value and if the values are equal then by decreasing keys
I tried :
res = {val[0] : val[1] for val in sorted(test_dict.items(), key = lambda x: (-x[1], -x[0]))}
I get the following error:
Traceback (most recent call last):
File "<string>", line 12, in <module>
File "<string>", line 12, in <lambda>
TypeError: bad operand type for unary -: 'str'
Solution 1:
Your keys are strings, you can't make those negative. Try this instead:
res = {val[0] : val[1] for val in
sorted(test_dict.items(), key=lambda x: (x[1], x[0]), reverse=True)}