0

I want to sort a dict, first by the value and then by the key. The key being a string.

Example,

>>> words = {'fall':4, 'down':4, 'was':3, 'a':3, 'zebra':2, 'bitter':1, 'betty':1}
>>> sorted(words.items(), key=itemgetter(1,0), reverse=True)
[('fall', 4), ('down', 4), ('was', 3), ('a', 3), ('zebra', 2), ('bitter', 1), ('betty', 1)]

As you can see above, the dict is getting sorted by value but not by the key.

Thanks.

Edit: I forgot to point out that I wanted the values to get sorted top to down and the key bottom to top.

Vijay
  • 111
  • 7
  • 1
    It looks sorted to me - 4, 4, 3, 3, 2, 1, 1. If values are equal they are sorted by the key. Everything is in reversed order, because of the `reverse=True` – nikihub Mar 02 '16 at 04:22
  • http://stackoverflow.com/questions/9001509/how-can-i-sort-a-dictionary-by-key – zedfoxus Mar 02 '16 at 04:22
  • `but not by the key` yes it is. what else would you have? – njzk2 Mar 02 '16 at 04:23
  • What I forgot to write was that I wanted the keys to be sorted the other way, that is, ascending. – Vijay Mar 02 '16 at 04:27

1 Answers1

2

This should do the trick. Take advantage of the fact that the values are numbers.

from operator import itemgetter

words = {'fall':4, 'down':4, 'was':3, 'a':3, 'zebra':2, 'bitter':1, 'betty':1}
sorted_words = [v for v in sorted(words.iteritems(), key=lambda(k, v): (-v, k))]
print(sorted_words)

Output:

[('down', 4), ('fall', 4), ('a', 3), ('was', 3), ('zebra', 2), ('betty', 1), ('bitter', 1)]
Kordi
  • 2,405
  • 1
  • 14
  • 13