擅长:python、mysql、java
<p>有点离题,但是:</p>
<pre><code>for i in temp.keys():
key = i
num = [int(frequency[key])]
tvalues += num
should just be:
tvalues = temp.values()
</code></pre>
<p>示例:</p>
<pre><code>>>> D = {'a':1, 'b':2, 'c':3, 'd':4}
>>> D.keys()
['a', 'c', 'b', 'd']
>>> D.values()
[1, 3, 2, 4]
>>> D.items()
[('a', 1), ('c', 3), ('b', 2), ('d', 4)]
>>>
</code></pre>
<p>看来你的代码可以改成这样:</p>
<pre><code>>>> D = {'a':1, 'b':2, 'c':3, 'd':4}
>>> def get_top_k(D, k):
... return sorted(D.items(), reverse=True, key=lambda x: x[1])[:k]
...
>>> get_top_k(D, 2)
[('d', 4), ('c', 3)]
>>>
</code></pre>