Sort python dictionaries with 'value' as primary key and 'key' as secondary

Viewed 1919

What I am trying to do here is to display characters according to number of occurrences in a string in descending order. If two characters share the same number of occurrences, then they should be displayed as per the alphabetic order.

So given a string, 'abaddbccdd', what I want to display as output is: ['d', 'a', 'b', 'c']

Here is what I have done so far:

>>> from collections import Counter
>>> s = 'abaddbccdd'
>>> b = Counter(s)
>>> b
Counter({'d': 4, 'a': 2, 'c': 2, 'b': 2})
>>> b.keys()
['a', 'c', 'b', 'd']
>>> c = sorted(b, key=b.get, reverse=True)
>>> c
['d', 'a', 'c', 'b']
>>>

But how to handle the second part? 'a', 'b' and 'c' all appear in the text exactly twice and are out of order. What is the best way (hopefully shortest too) to do this?

4 Answers
Related