Search code examples
pythonobjectminimum

How to get object minimum/maximum value of specific key in python?


I have a list like this:

list = [
    {'price': 2, 'amount': 34},
    {'price': 7, 'amount': 123},
    {'price': 5, 'amount': 495}
]

How to get object with minimum/maximum value of specific key in python? With this I can get the minimum value:

min(obj['price']  for obj in list) # 2

but what I want to get is a whole object

{'price': 2, 'amount':34}

How can I achieve this? Is there a simple way without foreach etc?


Solution

  • Use a key for your min function:

    from operator import itemgetter
    
    min(my_list, key=itemgetter('price'))
    

    Also don't use python's built-in key-words and/or data structure names as your variables and objects name. It will confuse the interpreter by shadowing the built-in names.