Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Get the Maximum Value from a Dictionary

Python Get the Maximum Value from a Dictionary

Document Object Reference Manual Python3 Examples

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

]

print

(

f

"Key with maximum value: {max_key}, Maximum value: {max_value}"

)

Code analysis:

  1. my_dict is a dictionary containing key-value pairs.
  2. max(my_dict, key=my_dict.get) Use max() function to get the key with the largest value in the dictionary.key=my_dict.get indicates that we compare based on the dictionary's values.
  3. max_key is the key with the largest value.
  4. max_value is obtained via max_key the maximum value retrieved from the dictionary.
  5. Finally, we print the key with the largest value and its corresponding value.

Output result:

Key with maximum value: b, Maximum value: 20

Document Object Reference Manual Python3 Examples