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 second maximum value in Dictionary
In this article, we will learn how to find the second maximum value in a Python dictionary. We'll explore three different approaches: using built-in sorting functions, manual sorting, and a brute-force method.
Problem statement ? We are given a dictionary with key-value pairs, and we need to find the second maximum value among all dictionary values.
Using sorted() Function
The simplest approach is to sort the dictionary values and access the second largest element using negative indexing ?
# input dictionary
example_dict = {"tutor": 3, "tutorials": 15, "point": 9, "tutorialspoint": 19}
# sorting the values and get the second last element
second_max = list(sorted(example_dict.values()))[-2]
print("Second maximum value:", second_max)
Second maximum value: 15
Using sort() Method
We can extract dictionary values into a list, sort them in-place, and then access the second largest element ?
example_dict = {"tutor": 3, "tutorials": 15, "point": 9, "tutorialspoint": 19}
# extract values into a list
values = list(example_dict.values())
# using built-in sort method
values.sort()
# second last element
print("Second largest element in the dictionary is:", values[-2])
Second largest element in the dictionary is: 15
Using Brute-Force Method
This approach finds the second maximum without using built-in sorting functions by tracking the maximum and second maximum values ?
example_dict = {"tutor": 3, "tutorials": 15, "point": 9, "tutorialspoint": 19}
values = list(example_dict.values())
# assuming max_ is equal to maximum of element at 0th and 1st index
# and second_max is the minimum among them
max_ = max(values[0], values[1])
second_max = min(values[0], values[1])
for i in range(2, len(values)):
# if found element is greater than max_
if values[i] > max_:
second_max = max_
max_ = values[i]
# if found element is greater than second_max
elif values[i] > second_max:
second_max = values[i]
print("Second highest number in the dictionary is:", second_max)
Second highest number in the dictionary is: 15
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
sorted() |
O(n log n) | O(n) | Simplicity and readability |
sort() |
O(n log n) | O(1) | In-place sorting |
| Brute-force | O(n) | O(1) | Efficiency with large datasets |
Conclusion
Use sorted() for simple, readable code. The brute-force method is most efficient for large datasets with O(n) complexity. Choose the approach based on your specific requirements for readability versus performance.
