user405892
user405892

Reputation: 197

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?

Upvotes: 7

Views: 17124

Answers (3)

RoadRunner
RoadRunner

Reputation: 26315

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']

Upvotes: 5

Austin Timmerman
Austin Timmerman

Reputation: 66

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.

Upvotes: 0

Brad Solomon
Brad Solomon

Reputation: 40878

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

Upvotes: 10

Related Questions