Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 321
clark Avatar asked Oct 12 '09 17:10

clark


2 Answers

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

like image 171
Nicholas Riley Avatar answered Sep 20 '22 06:09

Nicholas Riley


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)
like image 28
Corey Goldberg Avatar answered Sep 22 '22 06:09

Corey Goldberg