orders = {'U123':{'name':'Sumit Shukla', 'email':'[email protected]', 'phone':8608538199, 'product':['p1', 'p2', 'p5']},
'U121':{'name':'Ajay', 'email':'[email protected]', 'phone':7708538199, 'product':['p5', 'p2', 'p5']},
'U124':{'name':'Vijay', 'email':'[email protected]', 'phone':870853819, 'product':['p1', 'p2', 'p3']},
'U126':{'name':'Rahul', 'email':'rh_gmail.com', 'phone':8607858189, 'product':['p1', 'p5', 'p5']},
'U183':{'name':'Shree', 'email':'[email protected]', 'phone':8908938159, 'product':['p1', 'p1', 'p1']},
'U143':{'name':'shivani', 'email':'shivani@gmail', 'phone':855853019, 'product':['p5', 'p2', 'p5']}}
CodePudding user response:
assuming product_id
is p1, p2 etc:
productsBought = {}
for productId in orders:
order = orders[productId]["product"]
for product in order:
try:
productsBought[product] = 1 #try to increment the amount of products with that id bought
except:
productsBought[product] = 1 #the product hasn't been bought before, set the number of purchases to 1.
This will leave you with a dictionary that is in the format {product id : number of times purchased}
CodePudding user response:
you can use:
df=pd.DataFrame(orders).T.reset_index().explode('product')
final=df.groupby('product').agg({'index':'count'}).reset_index().rename(columns={'index':'order_count'}).to_dict('records')
print(final)
'''
[{'product': 'p1', 'order_count': 6}, {'product': 'p2', 'order_count': 4}, {'product': 'p3', 'order_count': 1}, {'product': 'p5', 'order_count': 7}]
'''