Skip to content
UniCircle
EasyCodingDictionaries and sorting

Group students by branch with defaultdict

Question PY-DIC-102

Each line of a hostel list has a roll number, a first name and a branch code. Print one line per branch, with branches in alphabetical order. Each line shows the branch, the number of students in it, and their names sorted alphabetically (keep duplicate names).

Constraints

  • 1 ≤ n ≤ 10^4
  • Names and branch codes are single words without spaces.

Input and output

Input
First line: n. Then n lines `roll name branch`.
Output
One line per branch: `BRANCH (count): name1, name2, ...`.

Examples

Input 1

5
22101 Riya CSE
22145 Arjun ECE
22011 Dev CSE
22190 Anaya CSE
22033 Kabir ECE

Output

CSE (3): Anaya, Dev, Riya
ECE (2): Arjun, Kabir

Branches come out in alphabetical order, and names are sorted within each branch.

Input 2

3
1 Tara ME
2 Tara ME
3 Aarav ME

Output

ME (3): Aarav, Tara, Tara

Duplicate names are kept.

Show hints
  • collections.defaultdict(list) creates an empty list the first time you use a new key.
  • sorted(d) iterates over the keys in sorted order.
Show the explanation
Python
groups = defaultdict(list)
for line in lines:
    _, name, branch = line.split()
    groups[branch].append(name)
for branch in sorted(groups):
    names = sorted(groups[branch])
    print(f"{branch} ({len(names)}): {', '.join(names)}")

What the question tests

  • `defaultdict(list)` removes the if branch not in groups: groups[branch] = [] boilerplate. dict.setdefault(branch, []).append(name) does the same with a plain dict.
  • Tuple unpacking, _, name, branch = line.split(). Use _ for a value you will not use.
  • Sorting. sorted() returns a new list and .sort() sorts in place. Both are stable and O(n log n). Python compares strings by code point, so uppercase letters sort before lowercase ones. The input uses consistent capitalisation here. In general, use key=str.lower for case-insensitive order.
  • `str.join` builds the comma-separated list in one pass. Repeatedly using += on strings is slower.

The total is O(n log n), dominated by sorting.

Original UniCircle question. Last reviewed 22 Oct 2026.