How to get the maximum value in a dictionary in Python?

Published on Aug. 22, 2023, 12:17 p.m.

To get the maximum value in a Python dictionary, you can use the built-in max() function, which returns the maximum value between two or more arguments. One way to use max() with a dictionary is to call max() on the dictionary’s values. Here’s an example:

my_dict = {'key1': 10, 'key2': 45, 'key3': 23}
max_value = max(my_dict.values())
print(max_value)  # Output: 45

In this example, max() is called with my_dict.values() as an argument, which returns a view object of the dictionary’s values. The resulting maximum value is stored in the max_value variable and printed to the console.

If you want to get the key of the maximum value in the dictionary, you can use a dictionary comprehension to create a new dictionary where the values are the keys and the keys are the values. You can then use max() on the resulting dictionary to get the key corresponding to the maximum value. Here’s an example:

my_dict = {'key1': 10, 'key2': 45, 'key3': 23}
max_key = max({v: k for k, v in my_dict.items()})
print(max_key)  # Output: 'key2'

In this example, a new dictionary comprehension v: k for k, v in my_dict.items() is created, where the keys and values from my_dict are swapped. max() is then called on the resulting dictionary to get the key with the maximum value, which is stored in the max_key variable and printed to the console.

Note that this method may not be efficient for large dictionaries, as it creates a new dictionary in memory. A more efficient way to get the key with the maximum value is to use the key argument in max() to define a custom function that returns the value for each key-value pair. Here’s an example:

my_dict = {'key1': 10, 'key2': 45, 'key3': 23}
max_key = max(my_dict, key=my_dict.get)
print(max_key)  # Output: 'key2'

In this example, max() is called on my_dict with the key argument set to my_dict.get, which returns the value for each key-value pair. The resulting key with the maximum value is

Tags: