Python Get top values in dictionary
<p>I have a dictionary called <code>wordCounts</code> which maps a word to how many times it occurred, how can I get the top <code>n</code> words in the dict while allowing more than <code>n</code> if there is a tie?</p>

<p>One solution could be:</p>

<pre><code>from collections import Counter, defaultdict


list_of_words = ['dog', 'cat', 'moo', 'dog', 'pun', 'pun']
def get_n_most_common(n, list_of_words):
    ct = Counter(list_of_words)
    d = defaultdict(list)
    for word, quantity in ct.items():
        d[quantity].append(word)
    most_common = sorted(d.keys(), reverse= True)
    return [(word, val) for val in most_common[:n] for word in d[val]]
</code></pre>

<p>And the tests:</p>

<pre><code> &gt;&gt; get_n_most_common(2, list_of_words)
 =&gt; [('pun', 2), ('dog', 2), ('moo', 1), ('cat', 1)]
 &gt;&gt; get_n_most_common(1, list_of_words)
 =&gt; [('pun', 2), ('dog', 2)]
</code></pre>

python dictionary