w3resource

Python: Get the maximum and minimum value in a dictionary

Python dictionary: Exercise-15 with Solution

Write a Python program to get the maximum and minimum values of a dictionary.

Sample Solution:-

Python Code:

# Create a dictionary 'my_dict' with key-value pairs.
my_dict = {'x': 500, 'y': 5874, 'z': 560}

# Find the key with the maximum value in 'my_dict' using the 'max' function and a lambda function.
# The 'key' argument specifies how the maximum value is determined.
key_max = max(my_dict.keys(), key=(lambda k: my_dict[k]))

# Find the key with the minimum value in 'my_dict' using the 'min' function and a lambda function.
# The 'key' argument specifies how the minimum value is determined.
key_min = min(my_dict.keys(), key=(lambda k: my_dict[k]))

# Print the maximum value by using the 'key_max' to access the corresponding value in 'my_dict'.
print('Maximum Value: ', my_dict[key_max])

# Print the minimum value by using the 'key_min' to access the corresponding value in 'my_dict'.
print('Minimum Value: ', my_dict[key_min])

Sample Output:

Maximum Value:  5874                                                                                          
Minimum Value:  500

Python Code Editor:

Previous: Write a Python program to sort a dictionary by key.
Next: Write a Python program to get a dictionary from an object's fields.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/dictionary/python-data-type-dictionary-exercise-15.php