查找值为数字高位的字典键

2024-06-26 13:42:56 发布

您现在位置:Python中文网/ 问答频道 /正文

给定Python dict的形式:

dict = {'Alice': 2341, 'Beth': 9102, 'Cecil': 3258, ......}

有没有一种简单的方法可以打印出具有最高数值的前x个键?也就是说:

Beth   9102
Cecil  3258

目前这是我的尝试:

max = 0
max_word = ""
for key, value in w.word_counts.iteritems():
    if value > max:
        if key not in stop_words:
            max = value
            max_word = key

print max_word

Tags: 方法keyinforifvaluedictmax
3条回答

使用^{}

>>> from collections import Counter
>>> d = {'Alice': 2341, 'Beth': 9102, 'Cecil': 3258}
>>> c = Counter(d)
>>> c.most_common(2)
[('Beth', 9102), ('Cecil', 3258)]

它使用的sortedO(n*log n))或heapq.nlargest(k)可能比sortedif k << nmax()if k==1快。你知道吗

>>> (sorted(dict.items(), key=lambda x:x[1]))[:2]
[('Alice', 2341), ('Cecil', 3258)]

我只需按第二个值对项目进行排序,然后选择第一个K元素:

d_items = sorted(d.items(), key=lambda x: -x[1])
print d_items[:2]
[('Beth', 9102), ('Cecil', 3258)]

这种方法的复杂性是O(N log N + K),与最优O(N + K log K)(仅使用快速选择和排序前K个元素)没有太大区别。你知道吗

相关问题 更多 >