Group Employees by Department

Medium ⏱ 12 min 53% acceptance ★★★★☆ 4.2
Write by_department(employees) where each employee is a (name, department) tuple, returning a plain dict mapping department → list of names in input order. Use collections.defaultdict(list) to avoid the if-key-missing dance, but convert to a normal dict before returning.

Examples

Example 1
Input
by_department([('Ana', 'Eng'), ('Raj', 'Sales'), ('Kim', 'Eng')])
Output
{'Eng': ['Ana', 'Kim'], 'Sales': ['Raj']}
Explanation

Names accumulate per department.

Constraints

  • Use defaultdict(list).
  • Return dict(result), not the defaultdict.

Topics

Modules & Packagescollections.defaultdict

Companies

LinkedInMicrosoftDeloitte

Hints

Hint 1

groups[dept].append(name) never KeyErrors on a defaultdict.

Hint 2

dict() strips the default factory.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.