Syntax error Python program to find the second maximum value in Dictionary

Python program to find the second maximum value in Dictionary



In this article, we will learn about the solution to the problem statement given below.

Problem statement − We are given two integers, we need to print the second maximum value in the dictionary

Now let’s observe the concept in the implementation below−

Approach 1 − Using sorted() function by negative indexes

Example

 Live Demo

#input
example_dict ={"tutor":3, "tutorials":15,
"point":9,"tutorialspoint":19}
# sorting the given list and get the second last element
print(list(sorted(example_dict.values()))[-2])

Output

15

Approach 2 − Here we use sort method on the list and then access the second largest element

Example

 Live Demo

list1 = [11,22,1,2,5,67,21,32]
# using built-in sort method
list1.sort()
# second last element
print("Second largest element in the list is:", list1[-2])

Output

Second largest element in the list is: 32

Approach 3 − Here we apply the brute-force method without using a built-in function

Example

 Live Demo

list1 = [11,22,1,2,5,67,21,32]
#assuming max_ is equal to maximum of element at 0th and 1st index
and secondmax is the minimum among them
max_=max(list1[0],list1[1])
secondmax=min(list1[0],list1[1])
for i in range(2,len(list1)):
   # if found element is greater than max_
   if list1[i]>max_:
      secondmax=max_
      max_=list1[i]
   #if found element is greator than secondmax
   else:
      if list1[i]>secondmax:
         secondmax=list1[i]
print("Second highest number is the list is : ",str(secondmax))

Output

Second highest number is the list is : 32

Conclusion

In this article, we have learned about how we can find the second maximum value in a dictionary ).

Updated on: 2020-07-11T11:28:51+05:30

704 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements