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>Convert <code>list</code> to <code>dict</code> with <em>key</em> as count and <em>value</em> as set of words. Find the <code>max</code> value of key, and it;s corresponding value</p>

<pre><code>from collections import defaultdict
my_list = [('AND', 1), ('BECAUSE', 1), ('OF', 1), ('AFRIAD', 1), ('NEVER', 1), ('CATS', 2), ('ARE', 2), ('FRIENDS', 1), ('DOGS', 2)]
my_dict = defaultdict(set)
for k, v in my_list:
    my_dict[v].add(k)

max_value = max(my_dict.keys())
print (my_dict[max_value], max_value)
# prints: (set(['CATS', 'ARE', 'DOGS']), 2)
</code></pre>

python string set max pair