7

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?

user405892
  • 197
  • 1
  • 1
  • 7

3 Answers3

8

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

Brad Solomon
  • 38,521
  • 31
  • 149
  • 235
5

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']
RoadRunner
  • 25,803
  • 6
  • 42
  • 75
0

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.