Philipp Braun Philipp Braun - 1 year ago 41
Python Question

Reducing an array of dictionaries based on condition and price

I would like to reduce the following list maybe using a lambda function. I know that I could first iterate over the entire list and split it into sublists based on the condition value. Then I would iterate over the sublists to get the minimum price.

price_list = [{'price':10.8,'condition':'new'},{'price':6.9,'condition':'new'},{'price':3.8,'condition':'used'},{'price':1.8,'condition':'used'}]

The final list should only contain one item per condition with the minimum price.

final_list = [{'price':6.9,'condition':'new'},{'price':1.8,'condition':'used'}]

Answer Source

You can do:

for c in {e['condition'] for e in price_list}:
    di['price']=min(e['price'] for e in price_list if e['condition']==c)

>>> li
[{'price': 6.9, 'condition': 'new'}, {'price': 1.8, 'condition': 'used'}]

As ShadowRanger points out, you do this is one iteration like so:

dd=defaultdict(lambda: float('inf'))
for itemdict in price_list:
    cond = itemdict['condition']
    dd[cond] = min(dd[cond], itemdict['price'])

for k, v in dd.items():
    li.append({'price':v, 'condition':k})