Find the highest 3 values in a dictionary in Python program

PythonServer Side ProgrammingProgramming

In this article, we will learn about the solution to the problem statement given below.

Problem statement − We are given a dictionary, and we need to print the 3 highest value in a dictionary.

There are two approaches as discussed below

Approach 1: Using Collections.counter() function

Example

 Live Demo

# collections module
from collections import Counter
# Dictionary
my_dict = {'T': 23, 'U': 22, 'T': 21,'O': 20, 'R': 32, 'S': 99}
k = Counter(my_dict)
# 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
S : 99
R : 32
U : 22

Here the mostcommon() method returns a list of the n most common elements and their counts from the most common to the least.

Approach 2 Using nlargest.heapq() function

Example

 Live Demo

# nlargest module
from heapq import nlargest
# Dictionary
my_dict = {'T': 23, 'U': 22, 'T': 21,'O': 20, 'R': 32, 'S': 99}
ThreeHighest = nlargest(3, my_dict, key = my_dict.get)
print("Dictionary with 3 highest values:")
print("Keys : Values")
for val in ThreeHighest:
   print(val, " : ", my_dict.get(val))

Output

Dictionary with 3 highest values:
Keys : Values
S    : 99
R    : 32
U    : 22

Here we used the n largest element that takes up three arguments, one is the no of elements to be selected and the other two arguments i.e. dictionary and its keys.

Conclusion

In this article, we have learned how we can find the highest 3 values in a dictionary

raja
Published on 23-Dec-2019 09:37:01
Advertisements