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>As the previous answer says, you can cast as a <code>Counter</code> to make this dataset easier to deal with.</p>

<pre><code>&gt;&gt;&gt; from collections import Counter
&gt;&gt;&gt; d = {"d":1,"c":2,"a":3,'b':3,'e':0,'f':1}
&gt;&gt;&gt; c = Counter(d)
&gt;&gt;&gt; c
Counter({'b': 3, 'a': 3, 'c': 2, 'f': 1, 'd': 1, 'e': 0})
</code></pre>

<p><code>Counter</code> has a <code>most_common(n)</code> method that will take the <code>n</code> most common elements. Note that it will <em>exclude</em> ties. Therefore:</p>

<pre><code>&gt;&gt;&gt; c.most_common(4)
[('b', 3), ('a', 3), ('c', 2), ('f', 1)]
</code></pre>

<p>To <em>include</em> all values equal to the nth element, you can do something like the following, without converting to a <code>Counter</code>. This is pretty messy, but it should do the trick.</p>

<pre><code>from collections import Counter

def most_common_inclusive(freq_dict, n):
    # find the nth most common value
    nth_most_common = sorted(c.values(), reverse=True)[n-1]
    return { k: v for k, v in c.items() if v &gt;= nth_most_common }
</code></pre>

<p>You can use as follows:</p>

<pre><code>&gt;&gt;&gt; d = {'b': 3, 'a': 3, 'c': 2, 'f': 1, 'd': 1, 'e': 0}
&gt;&gt;&gt; most_common_inclusive(d, 4)
{'d': 1, 'b': 3, 'c': 2, 'f': 1, 'a': 3}
</code></pre>

python dictionary