Python - find highest dictionary key with value greater than zero
<p>I have a dictionary</p>

<pre><code>{0: 12, 1: 1, 2: 13, 3: 7, 4: 0}
</code></pre>

<p>I want to find the highest dictionary key with a value greater than 0.</p>

<p>In this case, the answer is 3.</p>

<p>What's the best way to do this?</p>

<p>Use a genexpr to filter out the "bad" values, and <code>max</code> to keep the highest that remains:</p>

<pre><code># On Py2, use .iteritems() instead of .items()
max(k for k, v in mydict.items() if v &gt; 0)
</code></pre>

<p>Or if you need to have a default if no keys qualify without an exception being raised:</p>

<pre><code># Py3 max has default, which makes this super-easy:
max((k for k, v in mydict.items() if v &gt; 0), default=SOMEVALUEGOESHERE)

# Py2 doesn't have default; workaround is to catch exception and use a default (EAFP):
try:
    mymax = max(k for k, v in mydict.iteritems() if v &gt; 0)
except ValueError:
    mymax = SOMEVALUEGOESHERE

# Or if you can't do that for some reason, make a listcomp instead of genexpr
# and check for at least one surviving key before calling max (LBYL)
goodkeys = [k for k, v in mydict.iteritems() if v &gt; 0]
mymax = max(goodkeys) if goodkeys else SOMEVALUEGOESHERE
</code></pre>

python dictionary