Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 432
user405892 Avatar asked Dec 18 '17 03:12

user405892


People also ask

How do we find highest 2 values in a dictionary Python?

list(sorted(dict. values()))[-2] converts dict_values to list and return the second last element of the sorted list, i.e. the second largest value of dictionary. Was this answer helpful?

How do we find highest 2 values in a dictionary?

We can find the second largest value in a dictionary by sorting the values of the dictionaries and then retrieving the second last element from the sorted list.

Can dictionaries have multiple values per key?

General Idea: In Python, if we want a dictionary to have multiple values for a single key, we need to store these values in their own container within the dictionary. To do so, we need to use a container as a value and add our multiple values to that container. Common containers are lists, tuples, and sets.

Can Max return multiple values Python?

Passing Two or More Values to the Python max() MethodWhen two or more values are passed to the max() method, it returns the maximum or largest of them all. These arguments can be integers, floating-point values, characters or even strings.


2 Answers

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

like image 61
Brad Solomon Avatar answered Nov 07 '22 06:11

Brad Solomon


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']
like image 43
RoadRunner Avatar answered Nov 07 '22 04:11

RoadRunner