Aditya Aditya - 1 year ago 168
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: {'': '1620', '': '470', '': '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:

{'': '1620', '': '470', '': '1615'}


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


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

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download