48 — Shop — an inventory store
Guide 33 saved a list and 31 saved
records. A store grows that idea one step: a dict of items (each with price
and stock) plus a money balance, all in shop.json.
Steps
The shop is one JSON object with two parts: an
itemsdict mapping a name to{"price": N, "stock": N}, plus amoneybalance:
run it →{ "items": { "apple": {"price": 3, "stock": 10}, "banana": {"price": 5, "stock": 5}, "cherry": {"price": 2, "stock": 0} }, "money": 20 }The whole store. Save
shop.nmenext toshop.json.use file latestloadsjson_load/json_save, andos.path.existsstarts a fresh shop:
run it →# shop.nme — a small store kept in a JSON file. # Run: nme r shop # Type list, buy, sell, or quit. use file latest import os if os.path.exists("shop.json"): data = json_load("shop.json") else: data = {"items": {}, "money": 20} while True: show f"Money: {data['money']}" show "Commands: list, buy, sell, quit" ask command, "? " if command == "list": for name in data["items"]: item = data["items"][name] show f"{name}: {item['price']} each, {item['stock']} in stock" elif command == "buy" or command == "sell": ask name, "Item? " if name in data["items"]: item = data["items"][name] if command == "buy": if item["stock"] > 0: item["stock"] = item["stock"] - 1 data["money"] = data["money"] - item["price"] show f"Bought {name}" json_save("shop.json", data) else: show "Out of stock" else: item["stock"] = item["stock"] + 1 data["money"] = data["money"] + item["price"] show f"Sold {name}" json_save("shop.json", data) else: show "No such item" elif command == "quit": show "Bye!" break else: show "Unknown command"listwalks the dict withfor name in data["items"]:;buyandsellshare one branch viaor(guide 09). Buy pays the price and drops stock; sell refunds and adds;json_savewrites it back, so the store survives between runs.Run it and feed the commands through a pipe.
buy applepays 3 and drops stock to 9,sell applerefunds it:printf 'list\nbuy\napple\nsell\napple\nquit\n' | nme r shopMoney: 20 Commands: list, buy, sell, quit ? apple: 3 each, 10 in stock banana: 5 each, 5 in stock cherry: 2 each, 0 in stock Money: 20 Commands: list, buy, sell, quit ? Item? Bought apple Money: 17 Commands: list, buy, sell, quit ? Item? Sold apple Money: 20 Commands: list, buy, sell, quit ? Bye!
Try it yourself
Add a restock <name> <count> command that adds to an item's stock, or an
add <name> <price> command that inserts a new item and saves it.
What you learned
- A store is a dict of item dicts plus a money balance, all saved as JSON.
for name in data["items"]:lists a dict's keys and reads each item.buy/sellchange the balance and the stock, thenjson_savepersists.- A
quitcommand withbreakends thewhile True:menu.