The Python max() function is used to find the largest value in a list of values. The Python min() function is used to find the lowest value in a list. The list of values can contain either strings or numbers. You may encounter a situation where you want to find the minimum or maximum value in a list or a string.
Use Python's min() and max() to find smallest and largest values in your data. Call min() and max() with a single iterable or with any number of regular arguments. Use min() and max() with strings and dictionaries.
By using max() and dict. get() method we can easily get the Key with maximum value in a dictionary. To obtain the maximum value from the dictionary we can use the in-built max() function. In this example, we can use iterable and dict to get the key paired with the maximum value.
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 int
s):
import sys
lo,hi = sys.maxint,-sys.maxint-1
for 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!
One answer would be mapping your dicts to the value of interest inside a generator expression, and then applying the built-ins min
and max
.
myMax = max(d['price'] for d in myList)
myMin = min(d['price'] for d in myList)
can also use this:
from operator import itemgetter
lst = [{'price': 99, 'barcode': '2342355'}, {'price': 88, 'barcode': '2345566'}]
max(map(itemgetter('price'), lst))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With