Question 11 of 14intermediate🔧 ApplyLong Answer4 marks

Write a Python program to find the highest 2 values in a dictionary.

Correct Answer

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

Exercise: PROGRAMMING PROBLEMS | Q: 3 | (Page 19)
For More Understanding

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

  1. Step 1: Create a dictionary with key-value pairs

  2. Step 2: Extract all values using dict1.values() method and convert to list

  3. Step 3: Either sort the values in descending order using sorted(values, reverse=True) or use max() function twice

  4. Step 4: Access the first two elements for sorted method, or use max() and remove() for the second method

  5. Step 5: Print the highest 2 values