Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Group Words by First Letter Using defaultdict

Group a list of words into a dictionary keyed by their first character (case-insensitive), preserving original word order.

Python practice15 minList & Dictionary PatternsIntermediateLast updated March 20, 2026

Problem statement

Given a list of strings, implement group_by_first(words) that groups each word into a dictionary keyed by the lowercase of its first character. Each value should be a list of original words (preserving their original casing and input order) that start with that character. If a word is the empty string, use the empty string ('') as the key. If a word starts with a non-letter character, use that character (lowercased where applicable) as the key. The returned dictionary must have a deterministic key order: keys should be inserted in order sorted by their string representation (str(key)).

Task

Write a function that groups words by the lowercase of their first character and returns a deterministic dictionary ordered by key strings.

Examples

Basic grouping

Input

['apple', 'banana', 'apricot', 'Berry']

Output

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

Words starting with 'a' (case-insensitive) are grouped under 'a', 'banana' and 'Berry' under 'b'. Original word order is preserved inside each list.

Input format

A single parameter: words (list of strings).

Output format

A dict mapping each key (single-character string or '') to a list of words (strings).

Constraints

- Do not modify the original words. - Grouping is case-insensitive for determining the key (use .lower()). - Skip no words; empty strings are allowed and become a key ''. - The returned dict must have keys inserted in an order sorted by str(key) to ensure deterministic output.

Samples

Sample 1

Input

['Alpha', 'alpha', 'Beta']

Output

{'a': ['Alpha', 'alpha'], 'b': ['Beta']}

Both 'Alpha' and 'alpha' map to key 'a'.