How to get multiple max key values in a dictionary?

谁都会走 提交于 2021-02-02 09:23:11

问题


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?


回答1:


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().




回答2:


You could try collecting reverse value -> key pairs in a defaultdict, then output the values with the highest 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']



回答3:


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.



来源:https://stackoverflow.com/questions/47861737/how-to-get-multiple-max-key-values-in-a-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!