Fix Python – How to find the min/max value of a common key in a list of dicts?

Question

Asked By – Hank Fay

I have a list of dictionaries like so:

[{'price': 99, 'barcode': '2342355'}, {'price': 88, 'barcode': '2345566'}]

I want to find the min() and max() prices. Now, I can sort this easily enough using a key with a lambda expression (as found in another Stack Overflow post), so if there is no other way I’m not stuck. However, from what I’ve seen there is almost always a direct way in Python, so this is an opportunity for me to learn a bit more.

Now we will see solution for issue: How to find the min/max value of a common key in a list of dicts?


Answer

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.

This question is answered By – Hugh Bothwell

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0