Python 如何从字典中获取价值最高的3项?
假设我有这本字典:Python 如何从字典中获取价值最高的3项?,python,python-2.7,dictionary,max,Python,Python 2.7,Dictionary,Max,假设我有这本字典: {"A":3,"B":4,"H":1,"K":8,"T":0} 我想得到最高3个值的键。因此,在本例中,我将获得键:K,B和A您可以简单地使用来获取dict的键,如下所示: my_dict = {"A":3,"B":4,"H":1,"K":8,"T":0} my_keys =
{"A":3,"B":4,"H":1,"K":8,"T":0}
我想得到最高3个值的键。因此,在本例中,我将获得键:K
,B
和A
您可以简单地使用来获取dict
的键,如下所示:
my_dict = {"A":3,"B":4,"H":1,"K":8,"T":0}
my_keys = sorted(my_dict, key=my_dict.get, reverse=True)[:3]
# where `my_keys` holds the value:
# ['K', 'B', 'A']
或者,如果您也需要价值,也可以使用:
from collections import Counter
my_dict = {"A":3,"B":4,"H":1,"K":8,"T":0}
c = Counter(my_dict)
most_common = c.most_common(3) # returns top 3 pairs
# where `most_common` holds the value:
# [('K', 8), ('B', 4), ('A', 3)]
# For getting the keys from `most_common`:
my_keys = [key for key, val in most_common]
# where `my_keys` holds the value:
# ['K', 'B', 'A']
使用
d={“A”:3,“B”:4,“H”:1,“K”:8,“T”:0}
,你可以做dict(排序的(d.iteritems(),key=operator.itemgetter(1),reverse=True)[:3])。keys()
,打印['A',K',B']
不完全重复——这个问题要求3(或N)个最大的,其他问题的答案是按值排序的整个dict。在许多情况下,使用heapq.nlargest
可以更有效地获得N个最大值:import heapq;heapq.NLAGEST(3,my_dict,key=my_dict.get)
。是否可以将其扩展到获取中间3个项目
更容易的情况?只是好奇。