pythonintermediate10 minutes
Refactor a Function to Cleanly Process and Summarize Sales Data
Improve the clarity, efficiency, and readability of a Python function that processes a list of sales records and returns a summary of total sales by product category.
Challenge prompt
You are given a function that takes a list of sales records as input. Each record is a dictionary with keys: 'product', 'category', and 'amount'. The function calculates the total sales per category but is written in a convoluted way with redundant computations and unclear variable names. Refactor the function to keep the exact same behavior but improve its readability, maintainability, and efficiency. Ensure the function is Pythonic and avoids unnecessary loops or computations.
Guidance
- • Use clear and meaningful variable names.
- • Leverage appropriate Python data structures for aggregation (e.g., dictionaries or collections).
- • Avoid recalculating or looping over the same data multiple times.
- • Aim to write code that is easy to read and understand.
Hints
- • Consider using a dictionary to accumulate totals per category as you iterate through the sales records.
- • The built-in dict.get() method can help simplify updating totals without explicit conditional checks.
- • Avoid nested loops or multiple passes over the data when one will suffice.
Starter code
def summarize_sales(sales):
categories = []
for record in sales:
if record['category'] not in categories:
categories.append(record['category'])
totals = {}
for cat in categories:
total_amount = 0
for record in sales:
if record['category'] == cat:
total_amount += record['amount']
totals[cat] = total_amount
return totalsExpected output
{"electronics": 4500, "clothing": 3400}
Core concepts
data aggregationdictionary operationscode readabilityloop optimization
Challenge a Friend
Send this duel to someone else and see if they can solve it.