Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 508
j809809jkdljfja Avatar asked Aug 12 '26 00:08

j809809jkdljfja


1 Answers

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.

like image 82
Mazdak Avatar answered Aug 13 '26 13:08

Mazdak