Sort Counter by frequency, then alphabetically in Python

It sounds like your question is how to sort the entire list by frequency, then break ties alphabetically. You can sort the entire list like this:

>>> a = sorted(letter_count.items(), key=lambda item: (-item[1], item[0]))
>>> print(a)
# [('a', 2), ('b', 1), ('e', 1), ('h', 1), ('l', 1), ('p', 1), ('t', 1)]

If you want the output to be a dict still, you can convert it into a collections.OrderedDict:

>>> collections.OrderedDict(a)
# OrderedDict([('a', 2),
#              ('b', 1),
#              ('e', 1),
#              ('h', 1),
#              ('l', 1),
#              ('p', 1),
#              ('t', 1)])

This preserves the ordering, as you can see. 'a' is first because it's most frequent. Everything else is sorted alphabetically.


You can sort the input before passing it to the counter.

>>> Counter(sorted("alphabet")).most_common()
[('a', 2), ('b', 1), ('e', 1), ('h', 1), ('l', 1), ('p', 1), ('t', 1)]