Python 3.x: How do I sort a list of tuples that has the same second element (count) by string value?
<p>So for example</p>

<pre><code>['John','John','Mike','Mike','Kate','Kate']
</code></pre>

<p>Should return:</p>

<pre><code>[('John', 2), ('Kate', 2), ('Mike', 2)]
</code></pre>

<p>How can I write code so there is order instead of those three pairs just being in random order?</p>

<p>I need to sort the list of tuples by count from biggest to smallest unless there are ties, then I need to sort the times alphabetically.</p>

<p>This works:</p>

<pre><code>&gt;&gt;&gt; names = ['John','John','Mike','Mike','Kate','Kate']
&gt;&gt;&gt; sorted(Counter(names).items(), key=lambda item: (-item[1], item[0]))
[('John', 2), ('Kate', 2), ('Mike', 2)]
</code></pre>

<p>The counter's items will give you tuples of <code>(name, count)</code>.  Normally you'd use <code>Counter.most_common</code> 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.</p>

<p>Since we have to re-sort again anyway, we might as well use <code>sorted</code> 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 <code>(count, name)</code>.  However, since you want this to be <em>decreasing</em> by count, but <em>increasing</em> by name, the only thing we can do is return a tuple of the format <code>(-count, name)</code>.  This way, larger count will result in a lower value so it will sort <em>before</em> values with lower counts.</p>

python python-3.x