2

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?

j809809jkdljfja
  • 767
  • 2
  • 9
  • 25
  • Be careful to not name your objects with builtin function names e.g. `list` – Moses Koledoye Feb 02 '17 at 22:22
  • Possible duplicate of [In List of Dicts, find min() value of a common Dict field](http://stackoverflow.com/questions/5320871/in-list-of-dicts-find-min-value-of-a-common-dict-field) – DavidW Feb 02 '17 at 22:25
  • (Although most of the answers in the linked question only return the price so perhaps it isn't a great duplicate) – DavidW Feb 02 '17 at 22:29

2 Answers2

8

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.

Mazdak
  • 105,000
  • 18
  • 159
  • 188
8

To add on Kasramvd answer, you can also do this with lambda.

>>> foo = [
...     {'price': 2, 'amount': 34},
...     {'price': 7, 'amount': 123},
...     {'price': 5, 'amount': 495}
... ]
>>> max(foo, key=lambda x: x['price'])
{'amount': 123, 'price': 7}
>>> min(foo, key=lambda x: x['price'])
{'amount': 34, 'price': 2}
>>> 
Simeon Aleksov
  • 1,275
  • 1
  • 13
  • 25
  • 1
    Just of the sake of completion, I'd like to add that the `itemgetter` approach in the accepted answer is faster that the approach outlined here, i.e, using `lambda`. – Box Box Box Box Oct 28 '18 at 13:01