如何在字典中返回最高计数值?

时间:2015-06-06 01:17:19

标签: dictionary

我需要返回长度超过2的字典中的3个最高计数,我无法弄清楚如何处理它。这就是我试过的:

def highest3(diction) :
list = []
for key, value in diction.items() :
    if len(key) > 2 :
        list.append((key, value))
dictionary = dict(list)
print(dictionary)

3 个答案:

答案 0 :(得分:0)

您可以按递减顺序根据给定字典中的值对给定字典的进行排序,然后将结果切片为3个元素。

sample_dict = {'aid':1, 'alide':2, 'all':6, 'allies':2, 'allowed':1, 'almost':1, 'along':1, 'also':2, 'always':3}

for i in sorted(sample_dict.keys(), key = lambda x:sample_dict[x], reverse = True)[:3]:
    print i, sample_dict[i]

>>> all 6
    always 3
    allies 2

答案 1 :(得分:0)

您需要对列表进行排序并获得前3个值。

def top3(counts) :
    listA = []
    for k, v in counts.items():
        if len(k) > 2:
            listA.append((k, v))
    listA.sort(key=lambda tup: tup[1], reverse=True)
    listA = listA[:3]
    print(listA)

答案 2 :(得分:0)

首先获取密钥长度大于2的所有项目的列表:

>>> items = [item for item in counts.items() if len(item[0]) > 2]

现在按降序值和升序键对它们进行排序:

>>> items.sort(key=lambda item: (-item[1], item[0]))

最后,采取前三项:

>>> print(items[:3])
[('all', 6), ('always', 3), ('also', 2)]
相关问题