easy +8 pts

Group by Department

Build a nested dictionary that groups employee records by department.

Write a function `group_by_department(employees)` that takes a list of employee dictionaries. Each employee dictionary has at least the keys `'name'` and `'department'`. The function should return a dictionary where each key is a department name (string) and each value is a list of the employee dictionaries belonging to that department, in the same order they appear in the input list. Departments that have no employees should not appear in the result. The input list may be empty; in that case return an empty dictionary.

Constraints

- Input is a list of dictionaries, each with at least 'name' and 'department' keys. - The order of employees within each department must match the original order. - The order of departments in the output dictionary does not matter. - Time complexity: O(n), where n is the number of employees. - Memory complexity: O(n).

Example

>>> employees = [
...     {'name': 'Alice', 'department': 'Engineering'},
...     {'name': 'Bob', 'department': 'Sales'},
...     {'name': 'Carol', 'department': 'Engineering'}
... ]
>>> group_by_department(employees)
{'Engineering': [{'name': 'Alice', 'department': 'Engineering'}, {'name': 'Carol', 'department': 'Engineering'}], 'Sales': [{'name': 'Bob', 'department': 'Sales'}]}

>>> group_by_department([])
{}
8 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use a dictionary to map department names to lists.
Iterate over the input list and append each employee to the appropriate list.
Consider using `setdefault` or `defaultdict` to avoid key errors.
Remember to return the dictionary at the end.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.