Write a Python program to find the highest 2 values in a dictionary.
python
Program to find the highest 2 values in a dictionary
Creating a dictionary
dict1 = {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}
Method 1: Using sorted() function
values = list(dict1.values()) sorted_values = sorted(values, reverse=True) print("The highest 2 values are:", sorted_values[0], "and", sorted_values[1])
Method 2: Using max() function
val = list(dict1.values()) first_max = max(val) val.remove(first_max) second_max = max(val) print("The highest 2 values are:", first_max, "and", second_max)
Output:
The highest 2 values are: 95 and 92 The highest 2 values are: 95 and 92
Explanation
The question asks to find the highest 2 values in a dictionary. The context mentions that the values() method returns a list of values in the dictionary, and max() function can be used to find maximum values. Two approaches are shown: (1) Using sorted() with reverse=True to sort values in descending order and then accessing the first two elements, and (2) Using max() function to find the maximum value, removing it from the list, and then finding the next maximum. Both methods correctly identify 95 and 92 as the highest two values from the sample dictionary.
Solution Steps
Step 1: Create a dictionary with key-value pairs
Step 2: Extract all values using dict1.values() method and convert to list
Step 3: Either sort the values in descending order using sorted(values, reverse=True) or use max() function twice
Step 4: Access the first two elements for sorted method, or use max() and remove() for the second method
Step 5: Print the highest 2 values