我有一个功能:
def most_common(dictionary, integer):
'整数'必须是正数。此函数必须更新列表以包含字典中“整数”最常用的单词。
例如
>>> def most_common({'ONE': 1, 'TWO': 2, 'THREE': 3}, 2)
>>> {'TWO' : 2, 'THREE' : 3}
到目前为止,我为此函数编写的唯一代码是对字典进行排序。
答案 0 :(得分:3)
如果您想要最常用的字词,请使用collections.Counter
及其most_common
方法:
>>> import collections
>>> L = {'One' : 1, 'Two' : 2, 'Three' : 3}
>>> result = collections.Counter(L)
>>> dict(result.most_common(2)
{'Two': 2, 'Three': 3}
答案 1 :(得分:0)
dict(sorted([(k,v) for k, v in L.items()], key=lambda x: x[1])[-2:])