I have a list with orders. Each order contains products and their prices.
What I want is to write the shortest script possible to count total number of products sold and total amount of money earned. I’m looking for fields "count" and "total".
[
{
"id":1,
"items":[
{
"offerName":"name_1",
"count":6,
"prices":[
{
"costPerItem":129.0,
"total":774.0
}
]
},
{
"offerName":"name_2",
"count":1,
"prices":[
{
"costPerItem":120.0,
"total":120.0
}
]
}
]
},
{
"id":2,
"items":[
{
"offerName":"name_3",
"count":10,
"prices":[
{
"costPerItem":30.0,
"total":300.0
}
]
},
{
"offerName":"name_4",
"count":1,
"prices":[
{
"costPerItem":10.0,
"total":10.0
}
]
}
]
}
]
I got the right values, but I think there is a way to make the calculation more beautiful, without a lot of looping.
counts = []
prices = []
for order in sales_data:
products_list = order.get("items", [])
for offer in products_list:
counts.append(offer.get("count", 0))
prices.append(offer.get("prices", []))
total_earned=[]
for price in prices:
total = price[0].get("total", 0)
total_earned.append(total)
print(sum(counts))
print(sum(total_earned))
>Solution :
For making the code as brief as possible, list comprehensions can be used.
I have come up with a solution with only 2 lines of logic.
I have defined the initial count and price as zero, and using list comprehension, I am updating the count and price for each item every iteration using the assignment operator :=
sales_data = [
{
"id": 1,
"items": [
{
"offerName": "name_1",
"count": 6,
"prices": [
{
"costPerItem": 129,
"total": 774
}
]
},
{
"offerName": "name_2",
"count": 1,
"prices": [
{
"costPerItem": 120,
"total": 120
}
]
}
]
},
{
"id": 2,
"items": [
{
"offerName": "name_3",
"count": 10,
"prices": [
{
"costPerItem": 30,
"total": 300
}
]
},
{
"offerName": "name_4",
"count": 1,
"prices": [
{
"costPerItem": 10,
"total": 10
}
]
}
]
}
]
count, prices = 0, 0
[(count:=count+item['count'], prices:=prices+item['prices'][0]['total']) for sale in sales_data for item in sale['items']]
print('Count:', count, ', Prices:', prices)
This code outputs
Count: 18 , Prices: 1204