Reputation:
I have a dictionary like this: {'ex1': 3, 'ex2': 4, 'ex3': 3}
and I would like to sort it by values. So I do this: results = sorted(results.items(), key=lambda x: x[1], reverse=True)
. I put reverse=True
because I want it to sort in descending order.
so the code is something like this:
results = {'ex1': 3, 'ex2': 4, 'ex3': 3}
results = sorted(results.items(), key=lambda x: x[1], reverse=True)
for item in results:
print (item[0])
and the output is:
ex2
ex1
ex3
But the output I want is supposed to be look like this:
ex2
ex3
ex1
because in utf-8, ex3 is greater than ex1.
Actually what I want to say is that, when two keys have even values, I want to print them in descending order.
What am I doing wrong?
Thank you in advanced for your answer
Upvotes: 2
Views: 281
Reputation: 14536
This should work - the key function can return a tuple:
results = {'ex1': 3, 'ex2': 4, 'ex3': 3}
results = sorted(results.items(), key=lambda x: (x[1],x[0]), reverse=True)
for item in results:
print (item[0])
Gives output:
ex2
ex3
ex1
Upvotes: 2