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

Asked By: clark
||

Answer #1:

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

Answered By: Nicholas Riley

Answer #2:

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)
Answered By: Corey Goldberg

Answer #3:

Python's max function takes a key= parameter for a "measure" function.

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

print max(data, key=keymeasure)

Using an inline lambda to the same effect and same binding of local variables:

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

last alternative to bind in the local var into the anonymous key function

print max(data, key=(lambda k, mapping=data: mapping[k] and k))
Answered By: u0b34a0f6ae

Answer #4:

If I were you and speed was a big concern, I'd probably create a new container class "DictMax" that'd keep track of it's largest non-zero value elements by having an internal stack of indexes, where the top element of the stack is always the key of the largest element in the dictionary. That way you'd get the largest element in constant time everytime.

Answered By: Gubatron
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .



# More Articles