

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find the highest 3 values in a dictionary in Python program
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
# 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
# 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
- Related Questions & Answers
- Python program to find the highest 3 values in a dictionary
- Program to find the highest altitude of a point in Python
- Extract Unique dictionary values in Python Program
- Find keys with duplicate values in dictionary in Python
- How to find the average of non-zero values in a Python dictionary?
- How to search for the highest key from Python dictionary?
- Find n highest values in an object JavaScript
- Python program to find the sum of all items in a dictionary
- Python program to find the second maximum value in Dictionary
- How to replace values in a Python dictionary?
- Accessing Values of Dictionary in Python
- Extract Unique dictionary values in Python
- How do I format a string using a dictionary in Python 3?
- Program to find highest common factor of a list of elements in Python
- Find depth of a dictionary in Python
Advertisements