You can use operator.attrgetter and the key parameter of max
:
from operator import attrgetter
ancestor = max(nodes_ancestors, key=attrgetter('level'))
Below is a demonstration:
>>> from operator import attrgetter
>>> class Obj:
... def __init__(self, val):
... self.attr = val
...
>>> lst = [Obj(x) for x in range(10)]
>>> obj = max(lst, key=attrgetter('attr'))
>>> obj
<__main__.Obj object at 0x021C2290>
>>> obj.attr
9
>>>