Skip to content

Instantly share code, notes, and snippets.

@yamyamyuo
Last active October 11, 2018 06:05
Show Gist options
  • Save yamyamyuo/412bd1aeb4d73f62de43148f0f4d0b79 to your computer and use it in GitHub Desktop.
Save yamyamyuo/412bd1aeb4d73f62de43148f0f4d0b79 to your computer and use it in GitHub Desktop.
python group by
import os
from itertools import groupby
input2 = [
{'dept': '001', 'sku': 'foo', 'transId': 'uniqueId1', 'qty': 100},
{'dept': '001', 'sku': 'bar', 'transId': 'uniqueId2', 'qty': 200},
{'dept': '001', 'sku': 'foo', 'transId': 'uniqueId3', 'qty': 300},
{'dept': '002', 'sku': 'baz', 'transId': 'uniqueId4', 'qty': 400},
{'dept': '002', 'sku': 'baz', 'transId': 'uniqueId5', 'qty': 500},
{'dept': '002', 'sku': 'qux', 'transId': 'uniqueId6', 'qty': 600},
{'dept': '003', 'sku': 'foo', 'transId': 'uniqueId7', 'qty': 700}
]
from itertools import groupby
from operator import itemgetter
grouper = itemgetter("dept", "sku")
result = []
for key, grp in groupby(sorted(input2, key = grouper), grouper):
temp_dict = dict(zip(["dept", "sku"], key))
temp_dict["qty"] = sum(item["qty"] for item in grp)
result.append(temp_dict)
from pprint import pprint
pprint(result)
"""
[{'dept': '001', 'qty': 200, 'sku': 'bar'},
{'dept': '001', 'qty': 400, 'sku': 'foo'},
{'dept': '002', 'qty': 900, 'sku': 'baz'},
{'dept': '002', 'qty': 600, 'sku': 'qux'},
{'dept': '003', 'qty': 700, 'sku': 'foo'}]
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment