w3resource

Python: Find the highest 3 values of corresponding keys in a dictionary


22. Find Highest 3 Values of Corresponding Keys in a Dictionary

Write a Python program to find the highest 3 values of corresponding keys in a dictionary.

Sample Solution:

Python Code:

# Import the 'nlargest' function from the 'heapq' module.
from heapq import nlargest

# Create a dictionary 'my_dict' with key-value pairs.
my_dict = {'a': 500, 'b': 5874, 'c': 560, 'd': 400, 'e': 5874, 'f': 20}

# Use the 'nlargest' function to find the three largest keys in the 'my_dict' dictionary based on their values.
# The 'key' argument specifies that the values should be used for comparison.
three_largest = nlargest(3, my_dict, key=my_dict.get)

# Print the three largest keys found in the 'my_dict' dictionary.
print(three_largest)
 

Sample Output:

['b', 'e', 'c']

For more Practice: Solve these Related Problems:

  • Write a Python program to extract the three highest values from a dictionary and return them as a sorted list.
  • Write a Python program to use heapq.nlargest to find the top three values in a dictionary.
  • Write a Python program to implement a function that returns the keys corresponding to the highest three values in a dictionary.
  • Write a Python program to sort a dictionary by value and then output the three largest key-value pairs.

Python Code Editor:

Previous: Write a Python program to create and display all combinations of letters, selecting each letter from a different key in a dictionary.
Next: Write a Python program to combine values in python list of dictionaries.

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.