w3resource

Python: Get the maximum and minimum value in a dictionary


15. Get Maximum and Minimum Values of a Dictionary

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

For more Practice: Solve these Related Problems:

  • Write a Python program to determine the maximum and minimum values in a dictionary using the max() and min() functions.
  • Write a Python program to iterate over dictionary values and print the maximum and minimum values.
  • Write a Python program to implement a function that returns a tuple containing the min and max values from a dictionary.
  • Write a Python program to use list comprehension to extract dictionary values and then find their maximum and minimum.

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.



Follow us on Facebook and Twitter for latest update.