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