In List of Dicts, find min() value of a common Dict field In List of Dicts, find min() value of a common Dict field python python

In List of Dicts, find min() value of a common Dict field


lst = [{'price': 99, 'barcode': '2342355'}, {'price': 88, 'barcode': '2345566'}]maxPricedItem = max(lst, key=lambda x:x['price'])minPricedItem = min(lst, key=lambda x:x['price'])

This tells you not just what the max price is but also which item is most expensive.


There are several options. Here is a straight-forward one:

seq = [x['the_key'] for x in dict_list]min(seq)max(seq)

[Edit]

If you only wanted to iterate through the list once, you could try this (assuming the values could be represented as ints):

import syslo,hi = sys.maxint,-sys.maxint-1for x in (item['the_key'] for item in dict_list):    lo,hi = min(x,lo),max(x,hi)


I think the most direct (and most Pythonic) expression would be something like:

min_price = min(item['price'] for item in items)

This avoids the overhead of sorting the list -- and, by using a generator expression, instead of a list comprehension -- actually avoids creating any lists, as well. Efficient, direct, readable... Pythonic!