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>While the more pythonic solutions are certainly easier on the eye, unfortunately the requirement for two scans, or building data-structures you don't really want is significantly slower.</p>

<p>The following fairly boring solution is about ~55% faster than the dict solution, and ~70% faster than the comprehension based solutions based on the provided example data (and my implementations, machine, benchmarking etc.)</p>

<p>This almost certainly down to the single scan here rather than two.</p>

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


def linear_scan(word_occs):
    max_val = 0
    max_set = None

    for word, occ in word_occs:
        if occ == max_val:
            max_set.add(word)

        elif occ &gt; max_val:
            max_val, max_set = occ, {word}

    return max_set, max_val
</code></pre>

<p>To be fair, they are all blazing fast and in your case readability might be more important.</p>

python string set max pair