Write a Python Program to Find The Highest 3 Values of Corresponding Keys in a Dictionary

Hi, in this article lets solve Python Program to Find The Highest 3 Values of Corresponding Keys in a Dictionary

The problem statement : Given a dictionary having keys and values as integers. You should try to find the highest 3 values and their associated keys and print it.

 

dictionary of fruits

 

 

For Example : In a fruit stall you want to find the first 3 fruits that are costlier.

Now once we understand the problem statement, lets try to solve this.


Below is the program to find Find The Highest 3 Values of Corresponding Keys in a Dictionary.


Phase 1 : Create a dictionary having key and value pairs, example fruits and their cost.

fruits = {"banana":50, "mango": 80, "papaya":30, "apple":300, "strawberry":90}
 
 
Phase 2 : Then sort the fruits by value, using sorted() function.
 
costly_fruits = sorted(fruits, key=fruits.get, reverse=True)
 
Phase 3 : After sorting the dictionary will be ascending order of key value pairs. Print the first three key, value pairs as highest.

print("Highest 3 Values of Corresponding Keys in a Dictionary is ...")
 
for index in range(3): 
    print(costly_fruits[index])
 
 
Final Program :  

fruits = {"banana":50, "mango": 80, "papaya":30, "apple":300, "strawberry":90}
 
costly_fruits = sorted(fruits, key=fruits.get, reverse=True)
 
print("Highest 3 Values of Corresponding Keys in a Dictionary is ...")
 
for index in range(3): 
    print(costly_fruits[index])
 
 
Conclusion : You can change the key and values to subjects and marks scored in each subject, try to find 3 highest marks subjects. Try this example by yourself and comment down if you have any issues.

Thank you for reading my articles.

Post a Comment

0 Comments