Reputation: 111
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.
Upvotes: 0
Views: 860
Reputation: 2465
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)]
Upvotes: 2