I have a list of dicts like this:
sales_per_store_per_day = [
{'date':'2014-06-01', 'store':'a', 'product1':10, 'product2':3, 'product3':15},
{'date':'2014-06-01', 'store':'b', 'product1':20, 'product2':4, 'product3':16},
{'date':'2014-06-02', 'store':'a', 'product1':30, 'product2':5, 'product3':17},
{'date':'2014-06-02', 'store':'b', 'product1':40, 'product2':6, 'product3':18},
]
How could I reduce this list to have a sum of products for each store, ignoring the date? The result for the above input would be:
sales_per_store = [
{'store':'a', 'product1':40, 'product2':8, 'product3':32},
{'store':'b', 'product1':60, 'product2':10, 'product3':34}
]
Version without
collections
- maybe more readable for begginers..
Use a
collections.defaultdict()
to track info per store, andcollections.Counter()
to ease summing of the numbers:counts
is aCounter()
instance built from each of the products in theinfo
dictionary; I'm assuming that everything except thestore
anddate
keys are product counts. It uses a dict comprehension to produce a copy with those two keys removed. Theby_store[info['store']]
looks up the current total counts for the given store (which default to a new, emptyCounter()
object).The last line then produces your desired output; new dictionaries with
'store'
and per-product counts, but you may want to just keep the dictionary mapping from store toCounter
objects.Demo: