I'm new Python and trying to implement code in a more Pythonic and efficient fashion. Given a dictionary with numeric keys and values, what is the best way to find the largest key with a non-zero value?
Thanks
Something like this should be reasonably fast:
>>> x = {0: 5, 1: 7, 2: 0}
>>> max(k for k, v in x.iteritems() if v != 0)
1
(removing the != 0
will be slightly faster still, but obscures the meaning somewhat.)
To get the largest key, you can use the max
function and inspect the keys like this:
max(x.iterkeys())
To filter out ones where the value is 0, you can use a generator expression:
(k for k, v in x.iteritems() if v != 0)
You can combine these to get what you are looking for (since max
takes only one argument, the parentheses around the generator expression can be dropped):
max(k for k, v in x.iteritems() if v != 0)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With