Python – Efficient way to find the largest key in a dictionary with non-zero value

dictionarypython

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

Best Answer

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.)