Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从字典中获取价值最高的3项?_Python_Python 2.7_Dictionary_Max - Fatal编程技术网

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个项目
更容易的情况?只是好奇。