Python program to find second maximum value in Dictionary
Last Updated :
23 Jul, 2024
Dictionaries in Python is same as Associative arrays or Maps in other languages. Unlike lists, dictionaries stores data in key-value pair.
Let's see how to find the second maximum value in a Python dictionary.
Method #1: Naive Approach:
A general approach is to find the largest value of the dictionary and then iterate over the dictionary maintaining the value that must be greater than all the other values and less than the maximum value.
Python3
# Python naive approach to find the
# second largest element in a dictionary
# creating a new dictionary
new_dict ={"google":12, "amazon":9, "flipkart":4, "gfg":13}
# maximum value
max = max(new_dict.values())
# iterate through the dictionary
max2 = 0
for v in new_dict.values():
if(v>max2 and v<max):
max2 = v
# print the second largest value
print(max2)
Method #2: Using sorted() method
We can find the second largest value in a dictionary by sorting the values of the dictionaries and then retrieving the second last element from the sorted list.
Python3
# Python code to find second largest
# element from a dictionary using sorted() method
# creating a new Dictionary
example_dict = {"mark": 13, "steve": 3, "bill": 6, "linus": 11}
# now directly print the second largest
# value in the dictionary
print("Output1:", sorted(example_dict.values())[-2])
# More than 1 keys with maximum value are present
example_dict = {"fb": 20, "whatsapp": 12, "instagram": 20, "oculus": 10}
print("Output2:", sorted(set(example_dict.values()), reverse=True)[-2])
OutputOutput1: 11
Output2: 12
Time complexity: O(nLogn)
Auxiliary Space: O(1)
Explanation: example_dict.values() gives list of all the values in the dictionary. sorted() method will sort the list of dict_values. list(sorted(example_dict.values()))[-2] converts dict_values to list and return the second last element of the sorted list, i.e. the second largest value of dictionary.
if more than one maximum values are present in the dictionary as shown in the 2nd example, converting the dictionary values to a set will eliminate the duplicates.
Method #3: Using heap
Another approach to find the second maximum value in a dictionary is to use the heap data structure. Heaps are binary trees for which every parent node has a value less than or equal to any of its children. This structure allows us to easily find the maximum element in the heap.
To find the second maximum value in a dictionary, we can use a heap to store the values of the dictionary, and then repeatedly extract the maximum element until we find the second maximum value.
Here is an example of how this can be implemented using the heapq module in Python:
Python
import heapq
# creating a new Dictionary
example_dict = {"mark": 13, "steve": 3, "bill": 6, "linus": 11}
# Find the second maximum value in the dictionary using heapq
second_max = heapq.nlargest(2, example_dict.values())[1]
print(second_max) # Output: 11
#This code is contributed by Edula Vinay Kumar Reddy
The time complexity of this approach is O(n*log(n)), where n is the number of elements in the dictionary. The space complexity is O(n), as we need to store all the values of the dictionary in the heap. If more than one similar value is there then convert to set then heapify.
Similar Reads
Python program to find the key of maximum value tuples in a dictionary Given a dictionary with values as tuples, the task is to write a python program to find the key of maximum value tuples. Examples: Input : test_dict = {'gfg' : ("a", 3), 'is' : ("c", 9), 'best' : ("k", 10), 'for' : ("p", 11), 'geeks' : ('m', 2)}Output : forExplanation : 11 is maximum value of tuple
6 min read
Python - Maximum record value key in dictionary Sometimes, while working with dictionary records, we can have a problem in which we need to find the key with maximum value of a particular key of nested records in list. This can have applications in domains such as web development and Machine Learning. Lets discuss certain ways in which this task
6 min read
Python program to find the highest 3 values in a dictionary Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key:value pair. Examples: Input : my_dict = {'A': 67, 'B': 23, 'C': 45, 'D': 56, 'E': 12, 'F': 69} Output :
5 min read
Second largest value in a Python Dictionary In this problem, we will find the second-largest value in the given dictionary. Examples: Input : {'one':5, 'two':1, 'three':6, 'four':10} Output : Second largest value of the dictionary is 6 Input : {1: 'Geeks', 'name': 'For', 3: 'Geeks'} Output : Second largest value of the dictionary is Geeks Pyt
2 min read
Python program to find Maximum value from dictionary whose key is present in the list Given a list with dictionary keys and a dictionary, extract maximum from dictionary values, whose key is present in list. Examples: Input : test_dict = {"Gfg": 4, "is" : 5, "best" : 10, "for" : 11, "geeks" : 3}, test_list = ["Gfg", "best", "geeks"] Output : 10 Explanation : Max value is 11, but not
6 min read