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

I am a new Python and trying to implement the code in a more Pythonic and efficient way. Given a dictionary with numeric keys and values, what is the best way to find the largest key with a nonzero value?

thanks

+6
python dictionary
source share
4 answers

Something like this should be fast enough:

>>> x = {0: 5, 1: 7, 2: 0} >>> max(k for k, v in x.iteritems() if v != 0) 1 

(deleting != 0 will be a little faster, but it will hide the meaning a little.)

+12
source share

To get the largest key, you can use the max function and test such keys as follows:

 max(x.iterkeys()) 

To filter where the value is 0, you can use the expression:

 (k for k, v in x.iteritems() if v != 0) 

You can combine them to get what you are looking for (since max takes only one argument, the brackets around the generator expression can be omitted):

 max(k for k, v in x.iteritems() if v != 0) 
+10
source share

The Python max function accepts the key= parameter for the measure function.

 data = {1: 25, 0: 75} def keymeasure(key): return data[key] and key print max(data, key=keymeasure) 

Using the built-in lambda for the same effect and the same local variable binding:

 print max(data, key=(lambda k: data[k] and k)) 

the last alternative to binding in a local variable var to an anonymous key function

 print max(data, key=(lambda k, mapping=data: mapping[k] and k)) 
+1
source share

If I were with you and speed was a big problem, I would probably create a new container class β€œDictMax” that will track its largest elements without zero, having an internal index stack, where the top element of the stack is always the key of the largest element in dictionary. This way you will get the biggest item in constant time every time.

0
source share

All Articles