-2

The API input is like

{
  "Fruits": [
    {
      "name": "Apple",
      "quantity": 2,
      "price": 24
    },
    {
      "name": "Banana",
      "quantity": 1,
      "price": 17
    }
  ],
}

when we give this JSON input to the API it has to calculate the order and The response should be like

{'order_total':41}
ioeshu
  • 75
  • 1
  • 1
  • 5
  • 1
    what have you tried? please provide [mcve]. Is it possible there are other values that need to be calculated like Vegetables? – depperm Feb 02 '22 at 12:10
  • 1
    Seems like you already managed to calculate the order total by hand. What do you need our help figuring out? – Håken Lid Feb 02 '22 at 12:11

2 Answers2

0
sum(fruit["price"] for fruit in fruit_dict["Fruits"])

if you want it in a result dict:

result_dict = {}
result_dict["order_total"] = sum(fruit["price"] for fruit in fruit_dict["Fruits"])
UnsignedFoo
  • 330
  • 3
  • 10
0

I think you made a mistake in order total.

import json


json_raw = """
{
  "Fruits": [
    {
      "name": "Apple",
      "quantity": 2,
      "price": 24
    },
    {
      "name": "Banana",
      "quantity": 1,
      "price": 17
    }
  ]
}

"""


data = json.loads(json_raw)
print(data)

total = 0
for fruit in data ["Fruits"]:
        total += fruit["quantity"] * fruit["price"]

print(f"Total : {total}")

order = {}
order["order_total"] = total

print(f"Generated json:{json.dumps(order)}")

Here the output that i got

nabil@LAPTOP:~/stackoverflow$ python3 compute-total.py
{'Fruits': [{'name': 'Apple', 'quantity': 2, 'price': 24}, {'name': 'Banana', 'quantity': 1, 'price': 17}]}
Total : 65
Generated json:{"order_total": 65}
nabil@LAPTOP:~/stackoverflow$
Nabil
  • 1,130
  • 5
  • 11