Hank Fay
Hank Fay

Reputation: 1804

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

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.

Upvotes: 155

Views: 137452

Answers (6)

vii
vii

Reputation: 523

And to add to this great page: the top answer in a generic convenient function:


def takeMaxFromDictList(listOfDicts: list, keyToLookAt: str) -> dict:
  return max( listOfDicts, key=lambda x: x[keyToLookAt] )

# -------------------------------------------------------------------

examplelist = [{'score': 0.995, 'label': 'buildings'},
               {'score': 0.002, 'label': 'mountain'},
               {'score': 0.001, 'label': 'forest'}]
 
print ( takeMaxFromDictList(examplelist, 'score') )

>>> {'score': 0.995, 'label': 'buildings'}

Upvotes: 0

carton.swing
carton.swing

Reputation: 1717

can also use this:

from operator import itemgetter

lst = [{'price': 99, 'barcode': '2342355'}, {'price': 88, 'barcode': '2345566'}]  
max(map(itemgetter('price'), lst))

Upvotes: 5

Hugh Bothwell
Hugh Bothwell

Reputation: 56674

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.

Upvotes: 390

dappawit
dappawit

Reputation: 12580

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 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)

Upvotes: 75

rlibby
rlibby

Reputation: 6021

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)

Upvotes: 15

dcrosta
dcrosta

Reputation: 26258

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!

Upvotes: 56

Related Questions