Open In App

Second largest value in a Python Dictionary

Last Updated : 13 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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)


Output:

Geeks

Time Complexity : O(n Log n) 
Auxiliary Space: O(n)

Approach #2 : Using Reverse sort function

  1. Define a dictionary with key-value pairs.
  2. Convert dictionary values to list.
  3. Use built-in reverse sort() function on list of dictionary values. 
  4. 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)


Output

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


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads