Python Collection Counter.most_common(n)
method returns the top n elements with their counts. However, if the counts for two elements is the same, how can I return the result sorted by alphabetical order?
For example: for a string like: BBBAAACCD
, for the "2-most common" elements, I want the result to be for specified n = 2
:
[('A', 3), ('B', 3), ('C', 2)]
and NOT:
[('B', 3), ('A', 3), ('C', 2)]
Notice that although A
and B
have the same frequency, A
comes before B
in the resultant list since it comes before B
in alphabetical order.
[('A', 3), ('B', 3), ('C', 2)]
How can I achieve that?