如何从字典中检索多个最大值以及键

时间:2019-02-23 06:47:48

标签: python dictionary

如何检索字典的最大值及其对应的键?

func configureMessageCollectionView() {

    messagesCollectionView.messagesDataSource = self
    messagesCollectionView.messageCellDelegate = self

    scrollsToBottomOnKeyboardBeginsEditing = true // default false
    maintainPositionOnKeyboardFrameChanged = true // default false

    messagesCollectionView.addSubview(refreshControl)
    refreshControl.addTarget(self, action: #selector(loadMoreMessages), for: .valueChanged)
}

我只能得到最大值,结果是5,这是预期的,但是我似乎也无法检索与最大值对应的键。在这种情况下,对应的键应为2和4。

5 个答案:

答案 0 :(得分:2)

您可以尝试一下,

my_dict = {1: 4, 2: 5, 3: 2, 4: 5, 5: 3}

max_number=max(my_dict.values())

d=dict((key,value) for key, value in my_dict.items() if value == max_number)

print(d)

这将输出为:

  

{2:5,4:5}

如果只想检索密钥,则可以做

l=list(key for key, value in my_dict.items() if value == max_number)
print(l)

这将为-

  

[2,4]

希望这对您有帮助!

答案 1 :(得分:1)

您可以构建一个由my_dict中的值索引的键列表的字典,以便可以将最大值映射到其对应的键列表:

d = {}
for k, v in my_dict.items():
    d.setdefault(v, []).append(k)
print(d[max(d)])

这将输出:

[2, 4]

答案 2 :(得分:0)

您可以使用operator.itemgetter

import operator
my_dict = {1: 4, 2: 5, 3: 2, 4: 5, 5: 3}

key_max =  max(my_dict.items(), key=operator.itemgetter(1))[0]
key_min =  min(my_dict.items(), key=operator.itemgetter(1))[0]
print key_max, key_min

输出

2 3

答案 3 :(得分:0)

您应该能够获得这样的信息:

my_dict = {1: 4, 2: 5, 3: 2, 4: 5, 5: 3}
maxValue = -1
maxValueIndex = -1

for key, value in my_dict.items():
     if value >= maxValue:
        maxValue = value
        maxValueIndex = key

number = my_dict[key]

print(number)

答案 4 :(得分:0)

您可以使用Counter

from collections import Counter

my_dict = {1: 4, 2: 5, 3: 2, 4: 5, 5: 3}

c = Counter(my_dict)

c.most_common(2)
# [(2, 5), (4, 5)]

[i for i, _ in c.most_common(2)]
# [2, 4]