【问题标题】:How to get the 3 items with the highest value from dictionary? [duplicate]如何从字典中获取价值最高的 3 个项目? [复制]
【发布时间】:2017-03-22 15:30:50
【问题描述】:

假设我有这本字典:

{"A":3,"B":4,"H":1,"K":8,"T":0}

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

【问题讨论】:

  • 使用d = {"A":3,"B":4,"H":1,"K":8,"T":0},你可以做dict(sorted(d.iteritems(), key=operator.itemgetter(1), reverse=True)[:3]).keys(),打印['A', 'K', 'B']
  • 不完全重复——这个问题要求 3(或 N)个最大的,另一个问题的答案是让整个 dict 按值排序。在许多情况下,您可以使用heapq.nlargest 更有效地获得最大的N:import heapq; heapq.nlargest(3, my_dict, key=my_dict.get)
  • 想知道这是否可以扩展以更轻松地覆盖getting middle 3 items 的情况?只是好奇。

标签: python python-2.7 dictionary max


【解决方案1】:

您可以简单地使用sorted() 获取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']

或者,如果您也需要价值,也可以使用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']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-17
    • 1970-01-01
    • 2016-05-09
    • 1970-01-01
    • 1970-01-01
    • 2019-04-23
    • 2020-10-06
    • 1970-01-01
    相关资源
    最近更新 更多