🎯 Goal
Turn this:
{'item': 'Toothpaste', 'price': 800}
{'item': 'Sunlight Detergent', 'price': 1200}
{'item': 'Indomie Noodles', 'price': 150}
Into this:
| Item | Price | Category |
| ------------------ | ----- | ------------- |
| Toothpaste | 800 | Personal Care |
| Sunlight Detergent | 1200 | Cleaning |
| Indomie Noodles | 150 | Food |
✅ Step 1: Add Keyword Category Dictionary
Paste this after expenses = []
in your file:
category_map = {
"tooth": "Personal Care",
"paste": "Personal Care",
"soap": "Personal Care",
"detergent": "Cleaning",
"omo": "Cleaning",
"colgate": "Personal Care",
"sunlight": "Cleaning",
"indomie": "Food",
"noodle": "Food",
"maggie": "Food",
"rice": "Food",
"milk": "Beverage",
"sugar": "Food",
"bread": "Food",
"mayonnaise": "Food",
"oil": "Food",
"pack": "General",
"cream": "Personal Care",
"shampoo": "Personal Care",
"brush": "Personal Care",
"chocolate": "Snack",
"stew": "Food",
"meat": "Food",
"fish": "Food",
}
✅ Step 2: Add Categorization Logic
Paste this after the loop that fills expenses
, but before your final print:
def categorize(item_name):
item_name = item_name.lower()
for keyword, category in category_map.items():
if keyword in item_name:
return category
return "Uncategorized"
for e in expenses:
e['category'] = categorize(e['item'])
✅ Step 3: Update Output
Replace your print and CSV save block with this:
print("\nStructured Data with Categories:")
for e in expenses:
print(f"{e['item']} - ₦{e['price']} - [{e['category']}]")
with open('expenses.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Item', 'Price', 'Category'])
for e in expenses:
writer.writerow([e['item'], e['price'], e['category']])
✅ Final Output Example
Structured Data with Categories:
Colgate Toothpaste - ₦800 - [Personal Care]
Sunlight Detergent - ₦1200 - [Cleaning]
Indomie Noodles - ₦150 - [Food]
Item,Price,Category
Colgate Toothpaste,800,Personal Care
Sunlight Detergent,1200,Cleaning
Indomie Noodles,150,Food