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 SO article), 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.
There are several options. Here is a straight-forward one:
[Edit]
If you only wanted to iterate through the list once, you could try this (assuming the values could be represented as
int
s):can also use this:
One answer would be mapping your dicts to the value of interest inside a generator expression, and then applying the built-ins
min
andmax
.I think the most direct (and most Pythonic) expression would be something like:
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!
This tells you not just what the max price is but also which item is most expensive.