Python dict key with max value
<p>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. </p>

<pre><code>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 "&lt;br&gt;rmip&lt;br&gt;"
print rmip 

del masterdict [rmip]

print "&lt;br&gt;masterdict after deletion&lt;br&gt;&lt;br&gt;"
print masterdict

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

print "&lt;br&gt;nnip&lt;br&gt;"
print nnip
</code></pre>

<p>But the output i get is:</p>

<blockquote>
  <p>masterdict
  {'192.168.100.102': '1620', '192.168.100.103': '470', '192.168.100.101': '1615'}</p>
  
  <p>rmip
  192.168.100.103</p>
  
  <p>masterdict after deletion
  {'192.168.100.102': '1620', '192.168.100.101': '1615'}</p>
  
  <p>nnip
  192.168.100.102 </p>
</blockquote>

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

<p>The values in your dictionary are strings so <code>max</code> 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...:</p>

<pre><code>rmip = max(masterdict, key=lambda key: int(masterdict[key])
</code></pre>

<p>Or change the values to <code>int</code> and then use your current max statement:</p>

<pre><code>masterdict = {k: int(v) for k, v in masterdict.items()}
rmip = max(masterdict, key=masterdict.get)
</code></pre>

python dictionary