Second largest value in a Python Dictionary
Last Updated :
13 Mar, 2023
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)
|
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
dictionary = { 1 : 'Geeks' , 'name' : 'For' , 3 : 'Geeks' }
val = list (dictionary.values())
val.sort(reverse = True )
res = val[ 1 ]
print (res)
|
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
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...