We are given a string of words and the goal is to group these words into a dictionary where each key is the first character of a word and the corresponding value is a list of all words starting with that character. For example, in "Hello World", the words "Hello" and "World" start with 'H' and 'W' respectively, so the result is {'H': ['Hello'], 'W': ['World']}. Let's explore different ways to implement this efficiently in Python.
Using collections.defaultdict
defaultdict from the collections module automatically create empty lists for new keys. As you loop through each word, it appends the word to the list based on its first character. It's highly efficient and it maintains insertion order.
from collections import defaultdict
t = "Hello World"
res = defaultdict(list)
for w in t.split():
res[w[0]].append(w)
print(dict(res))
Output
{'H': ['Hello'], 'W': ['World']}
Explanation:
- defaultdict(list) creates a dictionary with default empty lists for new keys.
- t.split() splits the string t into ['Hello', 'World'].
- for each word w, append it to res[w[0]], where w[0] is the first character of the word.
Using dict.setdefault()
setdefault() is a dictionary method that simplifies inserting a key if it doesn't exist. It returns the value if the key exists or sets it to a default (like an empty list) if it doesn't. This avoids if-else logic and is great when you want a clean, built-in way to group values by keys without importing anything.
t = "Welcome to GeeksForGeeks"
res = {}
for w in t.split():
res.setdefault(w[0], []).append(w)
print(res)
Output
{'W': ['Welcome'], 't': ['to'], 'G': ['GeeksForGeeks']}
Explanation:
- t.split() splits the string t into ['Welcome', 'to', 'GeeksForGeeks'].
- res.setdefault(w[0], []) ensures the key w[0] (first letter of the word) exists with an empty list if it doesn't.
- append(w) adds the word w to the list at res[w[0]].
Using if condition
This classic approach manually checks if a key (the first character) exists in the dictionary. If it does, it appends the word to the list otherwise, it creates a new list. It’s great for beginners because of its simplicity and it works efficiently while preserving word order.
t = "Hello World"
res = {}
for w in t.split():
first = w[0]
if first in res:
res[first].append(w)
else:
res[first] = [w]
print(res)
Output
{'H': ['Hello'], 'W': ['World']}
Explanation:
- t.split() splits the string t into ['Hello', 'World'].
- For each word w, get the first letter first, check if first exists as a key in res. If yes, append w to the list, else create a new key with a list containing w.
Using dictionary comprehension
This method first creates an ordered list of first characters to preserve input order, then uses dictionary comprehension to group matching words. It’s easy to understand but it re-checks all words for each key, making it less efficient. Still a good choice for short or readable scripts.
t = "Welcome to GeeksForGeeks"
w = t.split()
seen = []
for i in w:
ch = i[0]
if ch not in seen:
seen.append(ch)
res = {ch: [i for i in w if i.startswith(ch)] for ch in seen}
print(res)
Output
{'W': ['Welcome'], 't': ['to'], 'G': ['GeeksForGeeks']}
Explanation:
- t.split() splits the string t into ['Welcome', 'to', 'GeeksForGeeks'].
- seen is a list that keeps track of the first letter of each word.
- For each word i, get the first letter ch and if ch is not in seen, append it.