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
Python3
dictionary = { 1 : 'Geeks' , 'name' : 'For' , 3 : 'Geeks' } val = list (dictionary.values()) val.sort() res = val[ - 2 ] print (res) |
Geeks
Time Complexity : O(n Log n)
Auxiliary Space: O(n)
Approach #2 : Using Reverse sort function
- Define a dictionary with key-value pairs.
- Convert dictionary values to list.
- Use built-in reverse sort() function on list of dictionary values.
- After reverse sorting of dictionary, print the index 1 of dictionary which is second largest value in dictionary.
Python3
# Python3 code using reverse sort method # code for finding second largest value in dictionary dictionary = { 1 : 'Geeks' , 'name' : 'For' , 3 : 'Geeks' } val = list (dictionary.values()) # using reverse sort() method val.sort(reverse = True ) res = val[ 1 ] print (res) # This code is contributed by Pratik Gupta (guptapratik) |
Geeks
Time Complexity : O(n * Log n), where n is the size of the dictionary
Auxiliary Space: O(n)
Please refer below post for more methods : Python program to find second maximum value in Dictionary