Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return the maximum value from a dictionary [duplicate]

I want to return the maximum value and its key from a dictionary, and I know that something like the following should do the trick

max(list.iteritems(), key=operator.itemgetter(1))

However in case that the maximum value in a dictionary is 6 and it happens that multiple keys have the same value .. it will always return the first one ! how can I make it return all the keys that has the maximum number as values along with the value. Here is an example of a dictionary with the same maximum value:

dic={0: 1.4984074067880424, 1: 1.0984074067880423, 2: 1.8984074067880425, 3: 2.2984074067880425, 4: 2.2984074067880425}
like image 750
Ophilia Avatar asked Feb 04 '17 18:02

Ophilia


People also ask

How do you return a max value in a dictionary?

Python find highest value in dictionary By using the built-in max() method. It is provided with the 'alpha_dict' variable to obtain the highest value from and to return the key from the given dictionary with the highest value, the dict. get() method is used.

What does .items return in dictionary?

The items() method returns a view object. The view object contains the key-value pairs of the dictionary, as tuples in a list. The view object will reflect any changes done to the dictionary, see example below.

Does dictionary allow duplicate values?

The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.


1 Answers

The solution using list comprehension:

dic={0: 1.4984074067880424, 1: 1.0984074067880423, 2: 1.8984074067880425, 3: 2.2984074067880425, 4: 2.2984074067880425}
max_value = max(dic.values())  # maximum value
max_keys = [k for k, v in dic.items() if v == max_value] # getting all keys containing the `maximum`

print(max_value, max_keys)

The output:

2.2984074067880425 [3, 4]
like image 73
RomanPerekhrest Avatar answered Sep 21 '22 00:09

RomanPerekhrest