In the previous CSV exercise, you saved a shopping list where each row contained an item’s name, quantity, price, and total.
Now, you will upgrade it using JSON, which is more flexible for storing structured data. Each product will be represented as a dictionary, and all items will be combined into a list. Your tasks:
total = quantity * price);shopping.json;shopping_sorted.json.Input example:
Enter item name (0 to stop): Pencil
Enter quantity: 5
Enter price per item: 1.5
Enter item name (0 to stop): Notebook
Enter quantity: 2
Enter price per item: 3
Enter item name (0 to stop): Eraser
Enter quantity: 4
Enter price per item: 0.5
Enter item name (0 to stop): 0
Data saved to shopping.json
Output example:
Top 3 Most Expensive Items:
- Pencil: $7.50
- Notebook: $6.00
- Eraser: $2.00
Sorted data saved to shopping_sorted.json
shopping.json:
[
{
"name": "Pencil",
"quantity": 5,
"price": 1.5,
"total": 7.5
},
{
"name": "Notebook",
"quantity": 2,
"price": 3.0,
"total": 6.0
},
{
"name": "Eraser",
"quantity": 4,
"price": 0.5,
"total": 2.0
}
]
shopping_sorted.json:
[
{
"name": "Pencil",
"quantity": 5,
"price": 1.5,
"total": 7.5
},
{
"name": "Notebook",
"quantity": 2,
"price": 3.0,
"total": 6.0
},
{
"name": "Eraser",
"quantity": 4,
"price": 0.5,
"total": 2.0
}
]
Answer example:
import json
# Step 1: Collect shopping items
items = []
while True:
name = input("Enter item name (0 to stop): ").strip()
if name == "0":
break
qty = int(input("Enter quantity: "))
price = float(input("Enter price per item: "))
total = qty * price
items.append({
"name": name,
"quantity": qty,
"price": price,
"total": total
})
# Step 2: Save data to JSON file
with open("shopping.json", "w", encoding="utf-8") as f:
json.dump(items, f, ensure_ascii=False, indent=2)
print("Data saved to shopping.json")
# Step 3: Read data back from JSON
with open("shopping.json", "r", encoding="utf-8") as f:
data = json.load(f)
# Step 4: Sort items by total (descending)
sorted_items = sorted(data, key=lambda x: x["total"], reverse=True)
# Step 5: Display top 3 items
print("nTop 3 Most Expensive Items:")
for item in sorted_items[:3]:
print(f"- {item['name']}: ${item['total']:.2f}")
# Step 6: Save sorted list to a new file
with open("shopping_sorted.json", "w", encoding="utf-8") as f:
json.dump(sorted_items, f, ensure_ascii=False, indent=2)
print("nSorted data saved to shopping_sorted.json")
This exercise can be thought of as having three connected phases: building the data, saving and reading, and sorting and rewriting.
In the first phase, we start by collecting several pieces of information from the user, each product has a name, a quantity, and a price. We use a loop so the user can keep entering items until they type “0” to stop. For every item, we calculate its total cost by multiplying quantity and price, and then store all this information in a dictionary like {"name": ..., "quantity": ..., "price": ..., "total": ...}. Each dictionary is appended to a list, giving us a neat list of dictionaries in memory — a structure that’s perfect for saving and processing later.
Next comes the saving stage. Here we use the JSON format, which fits Python data perfectly because a list of dictionaries in Python maps directly to a JSON array of objects. By calling json.dump(), we write the list to a file named shopping.json. Once saved, students can open the file and see how readable it is, each item appears as a small object with its name, quantity, price, and total.
After that, we move to the analysis phase. We reopen the same file with json.load() to convert it back into a Python list. The data looks exactly as it did before saving, showing that JSON preserves structure completely. Then, we use the sorted() function with a small lambda function to order the items by total cost in descending order. After sorting, we print out the top three most expensive items with their totals so students can see the result immediately. Finally, we save the sorted version to another file called shopping_sorted.json, giving us two files, one in original order, and another sorted by total value.
By completing this exercise, students not only practice reading and writing JSON files but also experience the full data cycle from user input to permanent storage, from analysis back to updated saving. It demonstrates the power of JSON: it doesn’t just store text or numbers but preserves the entire data structure, allowing programs to pick up exactly where they left off.