Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Group items by key using defaultdict

Use collections.defaultdict to group items into lists keyed by a function.

Python practice14 minModules & Standard LibraryIntermediateLast updated March 23, 2026

Problem statement

Given an iterable of items and a key function, return a dictionary that maps each key to a list of items that produce that key when the key function is applied. Use collections.defaultdict to build groups efficiently and maintain insertion order of items in each group. The key function will be called once per item. The returned value should be a normal dict (not a defaultdict) for predictable representation.

Task

Implement a group_by function that partitions an iterable into groups determined by a key function, preserving item order within each group.

Examples

Group numbers by parity

Input

group_by([1,2,3,4,5], lambda x: x % 2)

Output

{1: [1, 3, 5], 0: [2, 4]}

Items are grouped into odd (1) and even (0); order within each list follows the input order.

Input format

A list (or any iterable) of items and a key function: group_by(items, key_func)

Output format

A dict mapping keys to lists of items. Example: {key1: [item1, item2], key2: [item3]}

Constraints

Do not use third-party libraries. The key function will be applied to each item. Maintain the original order of items within each group.

Samples

Sample 1

Input

group_by(["apple","apricot","banana"], lambda s: s[0])

Output

{'a': ['apple', 'apricot'], 'b': ['banana']}

Groups by first letter of each string.