<p>您应该使用<a href="https://docs.python.org/3/library/heapq.html#heapq.nlargest" rel="nofollow noreferrer">^{<cd1>} function</a>来实现这一点:</p>
<pre><code>import heapq
from operator import itemgetter
top_names = dict(heapq.nlargest(5, names_dict.items(), key=itemgetter(1)))
</code></pre>
<p>这使用了一个更有效的算法(对于大小为N的dict,使用O(NlogK)和K个top items)将前5个项提取为<code>(key, value)</code>元组,然后将这些元组传递给<code>dict()</code>以创建新字典。在</p>
<p>演示:</p>
^{pr2}$
<p>您可能需要使用<a href="https://docs.python.org/3/library/collections.html#collections.Counter" rel="nofollow noreferrer">^{<cd4>} class</a>。<a href="https://docs.python.org/3/library/collections.html#collections.Counter.most_common" rel="nofollow noreferrer">^{<cd5>} method</a>会让你的用例变得很容易解决。该方法的实现在幕后使用<code>heapq.nlargest()</code>。在</p>
<p>这些是<em>而不是</em>特殊库,它们是Python标准库的一部分。否则,您必须自己实现一个<a href="https://en.wikipedia.org/wiki/Binary_heap" rel="nofollow noreferrer">binary heap</a>来实现这一点。除非您专门研究这个算法,否则重新实现您自己的算法是没有意义的,<a href="https://hg.python.org/cpython/file/3.5/Lib/heapq.py" rel="nofollow noreferrer">Python implementation</a>对某些关键函数使用<a href="https://hg.python.org/cpython/file/3.5/Modules/_heapqmodule.c" rel="nofollow noreferrer">extension written in C</a>进行了高度优化)。在</p>