Aditya Aditya - 2 months ago 5
Python Question

Python dict key with max value

I have a dictionary with IP addresses and their free memory space.
I'm trying to save an IP to one variable and the next highest one to another variable.

masterdict: {'192.168.100.102': '1620', '192.168.100.103': '470', '192.168.100.101': '1615'}

print masterdict

rmip = max(masterdict, key=masterdict.get)

print "<br>rmip<br>"
print rmip

del masterdict [rmip]

print "<br>masterdict after deletion<br><br>"
print masterdict

nnip = max(masterdict, key=masterdict.get)

print "<br>nnip<br>"
print nnip


But the output i get is:

masterdict
{'192.168.100.102': '1620', '192.168.100.103': '470', '192.168.100.101': '1615'}

rmip
192.168.100.103

masterdict after deletion
{'192.168.100.102': '1620', '192.168.100.101': '1615'}

nnip
192.168.100.102

Why is it printing 192.168.100.103 as rmip? Shouldn't it be the one with the highest value? i.e. 192.168.100.102 and then 101 as nnip?

Answer

The values in your dictionary are strings so max is comparing them as strings. If you want to compare them as integers, then you need to use the key function to convert the strings to integers...:

rmip = max(masterdict, key=lambda key: int(masterdict[key])

Or change the values to int and then use your current max statement:

masterdict = {k: int(v) for k, v in masterdict.items()}
rmip = max(masterdict, key=masterdict.get)