0

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.

AChampion
  • 29,683
  • 4
  • 59
  • 75
Shailab Singh
  • 89
  • 1
  • 1
  • 9
  • Can you give an example of what you have and what you want please? – Miguel Dec 28 '16 at 15:23
  • There are plenty of examples of sorting a dictionary by value, e.g.: https://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value without changing the internal `sort` and can easily be extended to cover the keys. – AChampion Dec 28 '16 at 15:25
  • Your `sorted` output is reversed. By default `sorted` does smallest to largest. – AChampion Dec 28 '16 at 18:06

1 Answers1

1

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)]
AChampion
  • 29,683
  • 4
  • 59
  • 75