Write a Python program to find the highest 2 values in a dictionary.
Question
Write a Python program to find the highest 2 values in a dictionary.
✨ Free AI Tools for You
Powered by Chatterbot AI
Answer
Here's a Python program to find the highest 2 values in a dictionary:
def find_highest_two_values(dictionary):
# Check if the dictionary has at least two items
if len(dictionary) < 2:
return "The dictionary does not have enough values."
# Sort the dictionary values in descending order and get the top two
sorted_values = sorted(dictionary.values(), reverse=True)
highest_two_values = sorted_values[:2]
return highest_two_values
# Sample dictionary
sample_dict = {'a': 10, 'b': 55, 'c': 23, 'd': 76, 'e': 42}
highest_two = find_highest_two_values(sample_dict)
print("The highest two values are:", highest_two)
In this program:
The function
find_highest_two_values
takes a dictionary as an input.It checks if the dictionary has at least two items.
It sorts the values of the dictionary in descending order.
It retrieves the top two values from the sorted list.
It returns the two highest values.
India's 1st AI Doubt Solver for CBSE, JEE, and NEET
Ask a Question for Freeand then it's just ₹212 a month