1

I want to find the next minimum value of the dictionary i wrote this code but it seems like there is an error with for loop any help ??

nodesdistfromsmartmeter = {'nodeA': 100, 'nodeB': 250, 'nodec': 300, 'nodeD': 50}

min_dist=min(nodesdistfromsmartmeter,key=nodesdistfromsmartmeter.get)
print("smalistdist",min_dist)
seondmin=0
for v in nodesdistfromsmartmeter():
 if(v>seondmin and v>min_dist):
    seondmin=v
    print(seondmin)

3 Answers3

1

Try this, it has some errors fixed.

nodesdistfromsmartmeter = {'nodeA': 100, 'nodeB': 250, 'nodec': 300, 'nodeD': 50}

min_dist=min(nodesdistfromsmartmeter,key=nodesdistfromsmartmeter.get)
print("smalistdist",min_dist)
secondmin=0
for v in nodesdistfromsmartmeter.keys():
 if(nodesdistfromsmartmeter[v]>secondmin and nodesdistfromsmartmeter[v]>nodesdistfromsmartmeter[min_dist]):
    secondmin=nodesdistfromsmartmeter[v]
    print(seondmin)

Output:

smalistdist nodeD
100
250
300
Hamza Khurshid
  • 765
  • 7
  • 18
1

Hope this helps :

from heapq import nsmallest

my_dict = {'nodeA': 100, 'nodeB': 250, 'nodec': 300, 'nodeD': 50}

print(nsmallest(2, my_dict.values())[-1])
AmirHmZ
  • 516
  • 3
  • 22
0

You just need to change this:

for v in nodesdistfromsmartmeter():

For this:

for v in nodesdistfromsmartmeter.values():
Nimantha
  • 6,405
  • 6
  • 28
  • 69
EnriqueBet
  • 1,482
  • 2
  • 15
  • 23