简体   繁体   English

如何在字典中获取多个最大键值?

[英]How to get multiple max key values in a dictionary?

Let's say I have a dictionary:假设我有一本字典:

data = {'a':1, 'b':2, 'c': 3, 'd': 3}

I want to get the maximum value(s) in the dictionary.我想获得字典中的最大值。 So far, I have been just doing:到目前为止,我一直在做:

max(zip(data.values(), data.keys()))[1]

but I'm aware that I could be missing another max value.但我知道我可能会错过另一个最大值。 What would be the most efficient way to approach this?解决这个问题的最有效方法是什么?

Based on your example, it seems like you're looking for the key(s) which map to the maximum value.根据您的示例,您似乎正在寻找映射到最大值的键。 You could use a list comprehension:您可以使用列表理解:

[k for k, v in data.items() if v == max(data.values())]
# ['c', 'd']

If you have a large dictionary, break this into two lines to avoid calculating max for as many items as you have:如果您有一本大字典,请将其分成两行,以避免计算尽可能多的项目的最大值:

mx = max(data.values())
[k for k, v in data.items() if v == mx]

In Python 2.x you will need .iteritems() .在 Python 2.x 中,您将需要.iteritems()

You could try collecting reverse value -> key pairs in a defaultdict , then output the values with the highest key:您可以尝试在defaultdict收集反向value -> key对,然后输出具有最高键的值:

from collections import defaultdict

def get_max_value(data):
    d = defaultdict(list)
    for key, value in data.items():
        d[value].append(key)
    return max(d.items())[1]

Which Outputs:哪些输出:

>>> get_max_value({'a':1, 'b':2, 'c': 3, 'd': 3})
['c', 'd']
>>> get_max_value({'a': 10, 'b': 10, 'c': 4, 'd': 5})
['a', 'b']

First of all, find what is the max value that occurs in the dictionary.首先,找出字典中出现的最大值是多少。 If you are trying to create a list of all the max value(s), then try something like this:如果您尝试创建所有最大值的列表,请尝试以下操作:

    data = {'a':1, 'b':2, 'c': 3, 'd': 3}
    max_value = data.get(max(data))
    list_num_max_value = []
    for letter in data:
      if data.get(letter) == max_value:
        list_num_max_value.append(max_value)
    print (list_num_max_value)

Please let me know if that's not what you are trying to do and I will guide you through the right process.如果这不是您想要做的,请告诉我,我将指导您完成正确的过程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM