pythonintermediate10 minutes
Refactor a Function for Summarizing Employee Sales Data
Improve the readability and efficiency of a given Python function that processes a list of employee sales records and returns a summary dictionary.
Challenge prompt
You are given a function that takes a list of dictionaries representing employee sales records. Each record contains 'employee_id' and 'sales' fields. The function returns a dictionary that sums total sales per employee. The existing code is functional but messy and inefficient. Refactor the function to improve code clarity, remove redundant operations, and maintain the exact output behavior.
Guidance
- • Focus on simplifying loops and minimizing dictionary lookups.
- • Use meaningful variable names and Python's dictionary methods.
- • Ensure the function runs efficiently on large input lists.
Hints
- • Consider using dict.get() to simplify your code when updating sales totals.
- • Avoid recalculating values or unnecessary intermediate variables.
- • Think about how you can combine operations inside a single loop.
Starter code
def summarize_sales(records):
result = {}
for record in records:
emp = record['employee_id']
sale = record['sales']
if emp in result:
result[emp] = result.get(emp, 0) + sale
else:
result[emp] = sale
return resultExpected output
{'e1': 450, 'e2': 300, 'e3': 150}
Core concepts
refactoringdictionary operationsloopscode readability
Challenge a Friend
Send this duel to someone else and see if they can solve it.