In: Computer Science
please solve by utilizing python
Define a function named checkOut which takes two JSON strings,
each representing a dictionary.
The first has the following structure,
{ "customer" : name , "cart" : [ item1, item2, ... ] }
The second has the following structure,
{ item1 : price1, item2 : price2, ... }
The function must return a JSON string representing the following
dictionary:
{ "customer" : name, "amount_due" : x }
where x is the sum of the prices of the items in the customer's
cart.
Example:
checkOut('{"customer":"Sally",
"cart":["milk","cookies"]}','{"milk":1.79,"cookies":3.99}') must
return '{"customer":"Sally", "amount_due":5.78}'
import json
def checkOut(items_json, price_json):
# Parses JSON string to python dictionary
items_dictionary = json.loads(items_json)
price_dictionary = json.loads(price_json)
amount_due = 0
# Iterating through the cart of items
for item in items_dictionary.get("cart"):
# If price of the item is mentioned
if item in price_dictionary:
amount_due += price_dictionary[item]
# Output dictionary
output_dictionary = {"customer": items_dictionary["customer"], "amount_due": amount_due}
# Converting Python dictionary to JSON String
output_json_string = json.dumps(output_dictionary)
return output_json_string
# Driver code
if __name__ == "__main__":
# json.dumps converts Python object into a JSON string
# Converting Python dictionary JSON string
items_json_string = json.dumps({"customer": "Sally", "cart": ["milk", "cookies"]})
price_json_string = json.dumps({"milk": 1.79, "cookies": 3.99})
print(checkOut(items_json_string, price_json_string))