如何从字典中获取最高值的 3 个项目?

Lir*_*hen 11 python dictionary max python-2.7

假设我有这本词典:

{"A":3,"B":4,"H":1,"K":8,"T":0}
Run Code Online (Sandbox Code Playgroud)

我想获得最高 3 个值的键。所以在这种情况下,我将获得密钥:K,BA

Moi*_*dri 23

您可以简单地使用sorted()来获取dictas的键:

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']
Run Code Online (Sandbox Code Playgroud)

或者,collections.Counter()如果您也需要价值,您可以使用:

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']
Run Code Online (Sandbox Code Playgroud)