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

Question:

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

||

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

Answered By: Nicholas Riley

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

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

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
  list=[1, 1, 2, 3,3]
  s={items:list.count(items)for items in list} ##occurrence of list 
  largest_value=max(k for k, v in s.items() if v != 0) #largest number occurrence 
  print(largest_value)
Answered By: Chethan H V
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.