Python 2.7超市购物程序:购物车存储方案技术咨询
Shopping Cart Storage: List vs Dict in Python 2.7
Hey there! Let’s break down the best way to store your supermarket shopping cart items (name, quantity, price) based on your Python 2.7 code.
Quick Comparison: List vs Dict
Let’s weigh the pros and cons of each structure for your use case:
Using a List
A list would store each cart item as a separate entry (like a dictionary or tuple), for example:
cart = [ {'name': 'asparagus', 'quantity': 2, 'price': 5}, {'name': 'broccoli', 'quantity': 1, 'price': 6} ]
- Pros: Maintains the exact order items were added, which can be nice for displaying the cart just as the user selected.
- Cons: To update an existing item (like adding more of the same product), you have to loop through the entire list to find a matching name. This gets slower as the cart grows and adds extra code overhead.
Using a Dict
A dict uses the product name as the key, with the value storing quantity and price (either as a list or another dict):
# Option 1: Value as a list [quantity, price] cart = {'asparagus': [2, 5], 'broccoli': [1, 6]} # Option 2: Value as a dict (more readable) cart = { 'asparagus': {'quantity': 2, 'price': 5}, 'broccoli': {'quantity': 1, 'price': 6} }
- Pros:
- Instantly look up or update any item by its name (no looping required)—perfect for when a user adds the same product multiple times.
- Cleaner, more efficient code for common cart tasks (updating quantity, checking if an item is already in the cart).
- Cons: Regular dicts in Python 2.7 don’t preserve insertion order. If order matters for displaying the cart, use
collections.OrderedDictinstead—it works like a dict but keeps track of the order items were added.
Recommendation: Use a Dict (or OrderedDict for Order)
For your supermarket program, a dict is the better choice. Here’s why:
- You’ll frequently need to check if a product is already in the cart (to update quantity instead of adding duplicates).
- Looking up items by name is far faster with a dict than a list.
- If you want to preserve the order items were added,
OrderedDictis a simple drop-in replacement that keeps your cart user-friendly.
Modified Code Example
Let’s adjust your existing code to implement an OrderedDict-based cart (with stock checks and cart display logic added):
from collections import OrderedDict inventory={'asparagus':[10,5],'broccoli':[15,6],'carrots':[18,7], 'apples':[20,5],'banana':[10,8],'berries':[30,3], 'eggs':[50,2],'mixed fruit juice':[0,8],'fish sticks':[25,12], 'ice cream':[32,6], 'apple juice':[40,7], 'orange juice':[30,8], 'grape juice':[10,9]} menu_list=["1. Search for the product", "2. See the basket","3. Check Out","4. Logout","5. Exit"] cart = OrderedDict() # Use regular dict if order doesn't matter: cart = {} def return_to_main(): print("\n=== Main Menu ===") for i in menu_list: print(i) main_menu = raw_input("Please choose one of the following services: ") if main_menu == "1": select = raw_input("Search for the product: ").lower() digit = 1 found_items = [] # Collect and display matching products for food in inventory: if select in food.lower(): found_items.append(food) print(f"{digit}. {food} | Stock: {inventory[food][0]} | Price: ${inventory[food][1]}") digit += 1 if found_items: # Let user select which item to add choice = raw_input("Enter the number of the product to add to cart: ") if choice.isdigit() and 1 <= int(choice) <= len(found_items): selected_food = found_items[int(choice)-1] # Check stock availability if inventory[selected_food][0] == 0: print("Sorry, this item is out of stock!") else: quantity = raw_input("Enter quantity to buy: ") if quantity.isdigit() and int(quantity) > 0 and int(quantity) <= inventory[selected_food][0]: qty = int(quantity) price = inventory[selected_food][1] # Update cart (add new item or increment quantity) if selected_food in cart: cart[selected_food]['quantity'] += qty else: cart[selected_food] = {'quantity': qty, 'price': price} print(f"Added {qty} {selected_food} to your cart!") else: print("Invalid quantity, or not enough stock available.") else: print("Invalid selection—please enter a number from the list.") else: print("No products found matching your search.") elif main_menu == "2": # Display the basket with totals if not cart: print("Your basket is empty!") else: print("\n=== Your Basket ===") total = 0 for item, details in cart.items(): subtotal = details['quantity'] * details['price'] total += subtotal print(f"- {item}: {details['quantity']} x ${details['price']} = ${subtotal}") print(f"Total: ${total}") elif main_menu == "5": print("Exiting program. Thanks for shopping!") return # Exit the loop else: print("Invalid option—please try again.") return_to_main() # Loop back to main menu # Start the program return_to_main()
Key Improvements
- Uses
OrderedDictto preserve the order items were added (optional but user-friendly). - Checks stock availability before allowing quantity selection.
- Updates existing cart items instead of adding duplicates.
- Displays the cart with subtotals and a grand total for checkout clarity.
内容的提问来源于stack exchange,提问作者Marshall Alife
相关产品推荐
相关产品推荐

