Get the object with the max attribute’s value in a list of objects

max() takes a key parameter, a function that when passed one of the objects returns the value by which to compare them.

Use operator.attrgetter() to get that value:

from operator import attrgetter

max(self.allPartners, key=attrgetter('attrOne'))

This returns the matching object for which that attribute is the maximum. If you wanted to store just that maximum value itself, you have two options:

  • Take the attribute from the returned object:

    max(self.allPartners, key=attrgetter('attrOne')).attrOne
    
  • Pass just the attributes instead to max() with a generator expression:

    max(p.attrOne for p in self.allPartners)
    

If you find that you need to order the One classes in various directions by the same attribute again and again (to find the minimum, maximum, sort them, etc.) you may want to make your class orderable as well.

To do that, you’ll need to implement some of the basic customization hooks Python will look for. With some extra trickery, you can get away with just the lower-than and equals operations, and by using the funtools.total_ordering class decorator:

from functools import total_ordering

@total_ordering
class One:
    # ...
    def __lt__(self, other):
        if not isinstance(other, type(self)): return NotImplemented
        return self.attrOne < other.attrOne

    def __eq__(self, other):
        if not isinstance(other, type(self)): return NotImplemented
        return self.attrOne == other.attrOne

Now your One class is orderable, entirely on the basis of attrOne; for the max() function, that means you can drop the key parameter altogether.

Leave a Comment