Python dictionaries allow you to store items as key-value pairs.
You can find the maximum value in a dictionary in Python using the max(yourdict.values()) statement.
Basic Example
yourdict = {
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": 5
}
maximum_value = max(yourdict.values())
maximum_value
Output
4
This tutorial teaches you how to find the maximum value in a dictionary in Python using the different methods and when it is appropriate to use each method.
Table of Contents
Using Max Function and Dict.values
The max() function returns the largest item in the iterable.
It accepts one mandatory parameter and two optional parameters.
iterable
– Mandatory – an iterable from which the maximum value needs to be identified
To get the maximum value from the dictionary,
- Pass the list of dictionary values to the max function using the
dict.values()
method. - From the list of values passed, the
max()
function returns the maximum value.
Use this method when you want to find the maximum value in a dictionary and do not need the key information of the maximum value.
Code
yourdict = {
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": 5
}
maximum_value = max(yourdict.values())
maximum_value
Output
4
Using Max Function and Operator.itemgetter
This section teaches you how to use the operator module’s itemgetter
to get the maximum value in a dictionary in Python.
The itemgetter()
method returns a callable object that fetches an item from its operand.
Finding the maximum value using the itemgetter()
works as explained below:
In the max()
function,
yourdict.items()
– Returns both key and value to the iteratorkey = operator.itemgetter(1)
– Specifies that the sorting function to find the maximum value should use the value in index1
. For example – a tuple withkey
andvalue
will be available during iteration. Key is available in index0
, and value is available in index1
. When you pass1
to theitemgetter()
, the item in index1
will be returned to the calling function. This means the value will be used to find the largest item- After finding the largest value, the
max()
function returns the tuple. For example,(‘five’, 5)
. You can use theindex -> [1]
to get the value from the tuple
Use this method when you want to find the maximum value in a dictionary and need the key of the maximum value.
Code
import operator
yourdict = {
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": 5
}
maximum_value_pair = max(yourdict.items(), key = operator.itemgetter(1))
maximum_value = maximum_value_pair[1]
maximum_value
Output
5
Get All Keys With Max Value
TO get all keys with the maximum value,
- Find the maximum value in a dictionary using
max(yourdict.values())
. - Using list comprehension, find all the keys with that specific value
Code
yourdict = {
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"fourr": 4
}
max_value = max(yourdict.values())
keys_with_max_values = [k for k,v in yourdict.items() if v == max_value]
keys_with_max_values
Output
['four', 'fourr']