Shailab Singh
Shailab Singh

Reputation: 91

I want to do some change in the sorted method(internally) in python3.X

I want to sort a dictionary on the basis of values while keeping the keys in the mind also. I want the keys to be in the order that I want (the keys should be in reverse sorted fashion for same values), but by default the keys are in sorted fashion for same values. How would I do that?

 dictionary = {'t':1, 'p':1, 'r':1, 'o':2, 'a':1}
 dictonary = sorted(dictonary.items(), key=itemgetter(1,0))

I get something like this. ('o', 2) ('t', 1) ('r', 1) ('p', 1) ('a', 1) but I want ('t', 1) ('r', 1) ('p', 1) ('a', 1) ('o', 2) that is for same values sort it reversely for same values.

Upvotes: 0

Views: 29

Answers (1)

AChampion
AChampion

Reputation: 30258

You can sort on a tuple of both your (value, key) using itemgetter with multiple args, e.g.:

>>> d = {'t':1, 'p':1, 'r':1, 'o':2, 'a':1}
>>> sorted(d.items(), key=itemgetter(1, 0))
[('a', 1), ('p', 1), ('r', 1), ('t', 1), ('o', 2)]

Updated OP changed expected output.
You can provide more control over the order with your own lambda function:

>>> sorted(d.items(), key=lambda x: (-x[1], x[0]), reverse=True)
[('t', 1), ('r', 1), ('p', 1), ('a', 1), ('o', 2)]

Upvotes: 1

Related Questions