Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to find the highest 3 values in a dictionary
In this article, we will learn how to find the highest 3 values in a dictionary using different Python approaches.
Problem Statement
Given a dictionary, we need to find the three highest values and display them along with their corresponding keys.
Using collections.Counter
The Counter class provides a most_common() method that returns the n most common elements and their counts ?
from collections import Counter
# Initial Dictionary
my_dict = {'a': 3, 'b': 4, 'c': 6, 'd': 5, 'e': 21}
counter = Counter(my_dict)
# Finding 3 highest values
highest = counter.most_common(3)
print("Dictionary with 3 highest values:")
print("Keys: Values")
for key, value in highest:
print(f"{key} : {value}")
Dictionary with 3 highest values: Keys: Values e : 21 c : 6 d : 5
Using heapq.nlargest()
The heapq.nlargest() function finds the n largest elements from an iterable based on a key function ?
import heapq
# Initial Dictionary
my_dict = {'a': 3, 'b': 4, 'c': 6, 'd': 5, 'e': 21}
# Finding 3 highest values using heapq
highest = heapq.nlargest(3, my_dict.items(), key=lambda x: x[1])
print("Dictionary with 3 highest values:")
print("Keys: Values")
for key, value in highest:
print(f"{key} : {value}")
Dictionary with 3 highest values: Keys: Values e : 21 c : 6 d : 5
Using sorted() with Lambda
We can sort the dictionary items by values in descending order and take the first 3 elements ?
# Initial Dictionary
my_dict = {'a': 3, 'b': 4, 'c': 6, 'd': 5, 'e': 21}
# Finding 3 highest values using sorted
highest = sorted(my_dict.items(), key=lambda x: x[1], reverse=True)[:3]
print("Dictionary with 3 highest values:")
print("Keys: Values")
for key, value in highest:
print(f"{key} : {value}")
Dictionary with 3 highest values: Keys: Values e : 21 c : 6 d : 5
Comparison
| Method | Time Complexity | Best For |
|---|---|---|
Counter.most_common() |
O(n + k log k) | When you need top k elements |
heapq.nlargest() |
O(n + k log n) | Large dictionaries |
sorted() |
O(n log n) | Small dictionaries or when you need all sorted |
Conclusion
Use heapq.nlargest() for large dictionaries as it's most efficient. For smaller dictionaries, sorted() provides a simple and readable solution. Counter.most_common() is ideal when working with frequency data.
