Harsh Maur
Harsh Maur

Reputation: 89

How to get a subset of a list based on conditions using python lambdas or list comprehensions

I have a list of dictionaries like this.

somelist = [
    { "store" : Amazon, "price": 1000},
    { "store" : Junglee, "price": 1200},
    { "store" : BestBuy, "price": 1300},
    { "store" : Amazon, "price": 900},
    { "store" : BestBuy, "price": 1200}
]

I want to filter it so that I get only those dictionaries which have unique stores and price being the lowest. So the final results should be

[
    { "store" : Amazon, "price": 900},
    { "store" : Junglee, "price": 1200},
    { "store" : BestBuy, "price": 1200}
]

What is the best way to do it in python?

Upvotes: 2

Views: 57

Answers (2)

chinskiy
chinskiy

Reputation: 2715

If store values will be strings like:

somelist = 
[
 { "store" : 'Amazon', "price": 1000},
 { "store" : 'Junglee', "price": 1200},
 { "store" : 'BestBuy', "price": 1300},
 { "store" : 'Amazon', "price": 900},
 { "store" : 'BestBuy', "price": 1200}
]

You can do something like this:

unique = set(map(lambda x: x['store'], somelist))
result = [min([__ for __ in somelist if __['store'] == _]) for _ in unique]

And result

[
 {'price': 900, 'store': 'Amazon'},
 {'price': 1200, 'store': 'Junglee'},
 {'price': 1200, 'store': 'BestBuy'}
]

Upvotes: 0

niemmi
niemmi

Reputation: 17263

You could collect the dictionaries to OrderedDict where key is the store and value is the lowest price. Then you can easily reconstruct the dictionaries with list comprehension:

from collections import OrderedDict

d = OrderedDict()
for x in somelist:
    d[x['store']] = min(d.get(x['store'], float('inf')), x['price'])

[{'store': k, 'price': v} for k, v in d.items()] # [{'price': 900, 'store': 'Amazon'}, {'price': 1200, 'store': 'Junglee'}, {'price': 1200, 'store': 'BestBuy'}]

If there's no need to preserve the ordering of the stores you could use standard dict as well.

Upvotes: 2

Related Questions