Python In 30 Days - Day 10
Day ten was about reading and writing CSV files, plus some extra work around sorting dictionaries by values. I'll say again, dictionaries can be so confusing! Glad I got to work through it though.
The Challenge:
You're building a menu management system using CSV files:
1. Write a function save_menu_to_csv(menu, filename) that:
- Takes a dictionary like your restaurant menu and writes it to a CSV
- The CSV should have two columns: item and price
- Includes the header row
2. Write a function load_menu_from_csv(filename) that:
- Reads the CSV back in
- Returns a proper Python dictionary
{"item": price}with prices as integers Handles FileNotFoundErrorgracefully
3. Write a function analyze_menu(menu) that returns a dictionary containing:
"most_expensive": name of the priciest item"cheapest": name of the cheapest item"average_price": average price rounded to 2 decimal places"items_by_price": the full menu sorted from most to least expensive, as a list of"Item - $X"strings
4. Save your restaurant menu to CSV, load it back into a fresh dictionary, run it through analyze_menu, and print the results cleanly
Things to figure out: how to iterate over a dictionary's items to write rows, how to sort a dictionary by its values, and how to find the max and min by value in a dictionary.
My Code:
import csv
import json
menu = [
{"item": "Burger", "price": 15},
{"item": "Fries", "price": 9},
{"item": "Brownie", "price": 7},
{"item": "Soft Drink", "price": 4},
]
def save_menu_csv(menu, filename):
with open(f"{filename}", "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["item", "price"])
writer.writeheader()
writer.writerows(menu)
print(f"Data saved to {filename}\n")
def load_menu_csv(filename):
try:
with open(f"{filename}", "r") as f:
reader = csv.DictReader(f)
new_menu = {row["item"]: row["price"] for row in reader}
menu = {k: int(v) for k, v in new_menu.items()}
print(f"{filename} loaded and parsed!\n")
return menu
except FileNotFoundError:
print(f"{filename} not found!")
def analyze_menu(menu):
largest = max(menu, key=menu.get)
smallest = min(menu, key=menu.get)
average = round(sum(menu.values()) / len(menu), 2)
sort = sorted(menu.items(), key=lambda item: item[1], reverse=True)
formatted = [f"{k} - ${v}" for k, v in sort]
analyzed = {
"most_expensive": largest,
"cheapest": smallest,
"average_price": average,
"items_by_price": formatted,
}
final = json.dumps(analyzed, indent=4)
return final
save_menu_csv(menu, "burgerjoint.csv")
printout = analyze_menu(load_menu_csv("burgerjoint.csv"))
print(printout)
Running The Code:
Data saved to burgerjoint.csv
burgerjoint.csv loaded and parsed!
{
"most_expensive": "Burger",
"cheapest": "Soft Drink",
"average_price": 8.75,
"items_by_price": [
"Burger - $15",
"Fries - $9",
"Brownie - $7",
"Soft Drink - $4"
]
}
Days 1–10 covered:
Functions → Lists & Dicts → List Comprehensions → String Methods → Error Handling → Classes → File I/O → JSON → APIs → CSV
Essentially, we've covered the full foundation of practical Python. The concepts from here get more interesting — less "how do I store data" and more "how do I write code that's elegant, efficient, and maintainable" - and following clean code principles.
The next ten days will cover:
Day 11: Decorators
Day 12: Generators & iterators
Day 13: Context managers
Day 14: *args and **kwargs
Day 15: Comprehensions — dict & set (plus nesting)
Day 16: Regular expressions
Day 17: Virtual environments & project structure
Day 18: Testing with pytest
Day 19: Working with databases (SQLite)
Day 20: Pulling it all together in a bigger project