Find Second Largest value in a dictionary in Python

In this tutorial, we will learn how to find the second largest value or number in a dictionary in Python.

Dictionaries are one of the main data types in Python others than lists, strings, booleans or integers. It contains key-value pairs enclosed in curly brackets ({ }).  The values of the key-value pairs can be accessed using the keys or the index of each key-value pair. For eg:

>>> d={'Mon':10,'Tue':20,'Sun':40}

To access the value of the element with key ‘Sun’, we use the following methods

  • Using Key ‘Sun’:
    d={'Mon':10,'Tue':20,'Sun':40}
    d['Sun']
    40
  • Using the index of element (key-value pair) which her, is 2.
    ld=d.values()
    ld[2]
    
    40

Python program to find Second Largest value in a dictionary

def Diction(d):
    s=d.values()
    l=sorted(s)
    u=l[-2]
    print("the second largest no. is")
    print(u)

f={'eggs':92,'bread':78,'milk':55,'yoghurt':29}
Diction(f)

Output

78

Code Explanation

We created a user-defined function ‘Diction’ with a parameter as a dictionary. Here, we have associated variable, ‘d’ with the dictionary. The main emphasis of this program is to find the second largest value of the element of the dictionary. We are using the following ways to do so:

  • A list is created of the values of the elements(key-value pairs) of the dictionary and stored in the variable s.
  • A variable l is assigned to the list after sorting the list ‘s‘ in ascending order.
  • Using slicing, we accessed the second last element of the newly sorted list and store it in variable u.
  • It is then printed.

In the last two steps, we created a dictionary which is assigned to variable f and used as a parameter while calling the function ‘Diction‘. Then we called the function to execute it.

Leave a Reply

Your email address will not be published. Required fields are marked *