Python Get the Maximum Value from a Dictionary
In Python, we can use the built-inmax()function to get the maximum value from a dictionary.max()The function can accept an iterable object and return the maximum value in it. For dictionaries, we can specifykeya parameter to determine whether to get the maximum value 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}")
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:
my_dictis a dictionary containing key-value pairs.max(my_dict, key=my_dict.get)Usemax()the 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 throughmax_keythe maximum value obtained from the dictionary.- Finally, we print the key with the largest value and the corresponding value.
Output:
Key with maximum value: b, Maximum value: 20Other Extensions
Python3 Examples