Home > Net >  How can I get 2 max value from list of objects in Python?
How can I get 2 max value from list of objects in Python?

Time:04-08

Let's say I have this list of objects:

value = [{'a': 0.864}, {'b': 0.902}, {'c': 1.174}, {'d': 1.162}]

All I want to do, is just get 2 objects with biggest value, like {'c': 1.174}, {'d': 1.162}

I can create such function:

def getTwoMaxValue(obj):
    extractedValues = []
    for i in obj:
        for attr, value in i.items():
            extractedValues.append(value)
    firstBiggestValue = max(extractedValues)
    extractedValues.remove(firstBiggestValue)
    secondBiggestValue = max(extractedValues)
...

But as you can see, it seems pretty long. Is there a way on how to do this writing less lines on code?

CodePudding user response:

This is how I would do it:

def get_two_max_value(obj, n=2):
    return sorted(obj, key=lambda x: max(v for v in x.values()))[-n:]


value = [{'a': 0.864}, {'b': 0.902, 'e': 100}, {'c': 1.174}, {'d': 1.162}]
print(get_two_max_value(value))

Even returns the objects instead of the values themselves.

  • Related