Python Get the Maximum Value from a Dictionary
In Python, we can use the built-in max() function to get the maximum value from a dictionary.max() The function accepts an iterable and returns the maximum value among it. For a dictionary, we can specify key parameter to decide whether to get the maximum based on keys or values.
Suppose we have a dictionary and we want to get the key-value pair with the largest value.
Example
my_dict
=
{
'a'
:
10
,
'b'
:
20
,
'c'
:
5
}
max_key
=
max
(
my_dict
,
key
=
my_dict.
get
)
max_value
=
my_dict
[
max_key
]
(
f
"Key with maximum value: {max_key}, Maximum value: {max_value}"
)
Code analysis:
my_dictis a dictionary containing key-value pairs.max(my_dict, key=my_dict.get)Usemax()function to get the key with the largest value in the dictionary.key=my_dict.getindicates that we compare based on the dictionary's values.max_keyis the key with the largest value.max_valueis obtained viamax_keythe maximum value retrieved from the dictionary.- Finally, we print the key with the largest value and its corresponding value.
Output result:
Key with maximum value: b, Maximum value: 20
Python3 Examples