Python program to find the highest 3 values in a dictionary


In this article, we will learn about the solution and approach to solve the given problem statement.

Problem statement

Given a dictionary, we need to find the three highest valued values and display them.

Approach 1 − Using the collections module ( Counter function )

Example

 Live Demo

from collections import Counter
# Initial Dictionary
my_dict = {'t': 3, 'u': 4, 't': 6, 'o': 5, 'r': 21}
k = Counter(my_dict)
# Finding 3 highest values
high = k.most_common(3)
print("Dictionary with 3 highest values:")
print("Keys: Values")
for i in high:
   print(i[0]," :",i[1]," ")

Output

Dictionary with 3 highest values:
Keys: Values
r : 21
t : 6
o : 5

Approach 2 − Using the heapq module ( nlargest function )

Example

 Live Demo

from collections import Counter
# Initial Dictionary
my_dict = {'t': 3, 'u': 4, 't': 6, 'o': 5, 'r': 21}
k = Counter(my_dict)
# Finding 3 highest values
high = k.most_common(3)
print("Dictionary with 3 highest values:")
print("Keys: Values")
for i in high:
   print(i[0]," :",i[1]," ")

Output

Dictionary with 3 highest values:
Keys: Values
r : 21
t : 6
o : 5

Conclusion

In this article, we learned about the approach to convert a decimal number to a binary number.

Updated on: 04-Jul-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements