This works:
>>> names = ['John','John','Mike','Mike','Kate','Kate']
>>> sorted(Counter(names).items(), key=lambda item: (-item[1], item[0]))
[('John', 2), ('Kate', 2), ('Mike', 2)]
The counter's items will give you tuples of (name, count)
. Normally you'd use Counter.most_common
to get the items in order of their counts, but as far as I can tell, it only sorts by count and disregards any key (name) information in the sorting.
Since we have to re-sort again anyway, we might as well use sorted
on the items instead. Since tuples sort lexicographically, and you want to sort primarily by the count, the key function should return a tuple of the format (count, name)
. However, since you want this to be decreasing by count, but increasing by name, the only thing we can do is return a tuple of the format (-count, name)
. This way, larger count will result in a lower value so it will sort before values with lower counts.