Python-selecting specified items from dictionary list
Question: Let's say I have list of cars:

    
    
    car=[{'model':'ferrari', 'color': 'red', 'price':1200},
    {'model':'lamborgini', 'color': 'blue', 'price':2000},
    {'model':'ferrari', 'color': 'yellow', 'price':1000},
    {'model':'ferrari', 'color': 'yellow', 'price':500}]
    

I want to select the cheapest car for every model-color combination(cheapest
red lamborgini, cheapest green ferrari etc) and put them in new list.

The output should be:

    
    
    [{'model':'ferrari', 'color': 'red', 'price':1200},
    {'model':'lamborgini', 'color': 'blue', 'price':2000},
    {'model':'ferrari', 'color': 'yellow', 'price':500}]
    

How can I do this?


Answer: It may be a good idea to create a helper datastructure.  
Here I use a dictionary with tuples of (model, color) as keys

    
    
    >>> car = [ {'model':'ferrari', 'color': 'red', 'price':1200},
    ... {'model':'lamborgini', 'color': 'blue', 'price':2000},
    ... {'model':'ferrari', 'color': 'yellow', 'price':1000},
    ... {'model':'ferrari', 'color': 'yellow', 'price':500} ]
    >>> from operator import itemgetter
    >>> from collections import defaultdict
    >>> D = defaultdict(list)
    >>> for item in car:
    ...     D[item['model'], item['color']].append(item)
    ... 
    >>> min(D['ferrari', 'yellow'], key=itemgetter('price'))
    {'color': 'yellow', 'model': 'ferrari', 'price': 500}
    

This means you don't need to scan the entire collection every time you make a
query

