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}
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.
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.
The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With