Finding Set of strings from list of pairs (string, int) with maximum int value
<p>I have a list of <code>(str,int)</code> pairs </p>

<p><code>list_word = [('AND', 1), ('BECAUSE', 1), ('OF', 1), ('AFRIAD', 1), ('NEVER', 1), ('CATS', 2), ('ARE', 2), ('FRIENDS', 1), ('DOGS', 2)]</code></p>

<p>This basically says how many times each word showed up in a text. </p>

<p>What I want to get is the set of words with maximum occurrence along with maximum occurrence number. So, in the above example, I want to get</p>

<p><code>(set(['CATS', 'DOGS','ARE']), 2)</code></p>

<p>The solution I can think of is looping through the list. But is there any elegant way of doing this?</p>

<p>Two linear scans, first to find the maximal element:</p>

<pre><code>maxcount = max(map(itemgetter(1), mylist)) 
</code></pre>

<p>then a second to pull out the values you care about:</p>

<pre><code>maxset = {word for word, count in mylist if count == maxcount}, maxcount
</code></pre>

<p>If you needed to get the sets for more than just the maximal count, you can use <a href="https://docs.python.org/3/library/collections.html#collections.defaultdict" rel="nofollow"><code>collections.defaultdict</code></a> to accumulate by count in a single pass:</p>

<pre><code>from collections import defaultdict

sets_by_count = defaultdict(set)

for word, count in mylist:
    sets_by_count[count].add(word)
</code></pre>

<p>Which can then be followed by <code>allcounts = sorted(sets_by_count.items(), key=itemgetter(0), reverse=True)</code> to get a <code>list</code> of <code>count, set</code> pairs, from highest to lowest count (with minimal sorting work, since it's sorting only a number of items equal to the unique counts, not all words).</p>

python string set max pair