Skip to content

Instantly share code, notes, and snippets.

@kazuhiko-hotta
Created July 26, 2016 15:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kazuhiko-hotta/bdba518adb60f75d4cbc7da7bd5c7486 to your computer and use it in GitHub Desktop.
Save kazuhiko-hotta/bdba518adb60f75d4cbc7da7bd5c7486 to your computer and use it in GitHub Desktop.
from collections import defaultdict
from pprint import pprint
data = [{'order_id': [17], 'product_id': 763},
{'order_id': [19], 'product_id': 822},
{'order_id': [19], 'product_id': 822},
{'order_id': [20], 'product_id': 994},
{'order_id': [20], 'product_id': 783},
{'order_id': [20], 'product_id': 783},
{'order_id': [21], 'product_id': 857},
{'order_id': [21], 'product_id': 822},
{'order_id': [26], 'product_id': 857}]
class Order(object):
def __init__(self, order):
self.order_id = order['order_id']
self.product_id = order['product_id']
def __hash__(self):
return hash((",".join([str(x) for x in self.order_id]), self.product_id))
def __eq__(self, other):
return self.order_id == other.order_id and self.product_id == other.product_id
if __name__ == "__main__":
purchase = defaultdict(lambda: {'product_id': 0, 'count': 0, 'order_counter': []})
orders = set([Order(o) for o in data])
for x in orders:
purchase[x.product_id]['product_id'] = x.product_id
purchase[x.product_id]['count'] += 1
purchase[x.product_id]['order_counter'].append(['order_id', x.order_id[0]])
result = [purchase[p] for p in purchase]
pprint(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment