25. Group words by first letter
Write a function group_words(words) that takes a list of words and returns a dictionary (a dict) that groups them
by their first letter.
- Each key is a first letter, in lower case:
"Bee"and"bat"both go under"b". - Each value is the list of words that start with that letter, written as they were given (capitals stay).
- Each list is in alphabetical order, ignoring case:
"bat"comes before"Bee", becauseacomes beforee. - Words that differ only in case, such as
"Ant"and"ant", keep the order they have inwords. A word given twice is kept twice. - If
wordsis empty, return an empty dictionary{}.
The order of the keys doesn't matter.
Example 1
Input
words = ["bee", "ant", "bat", "ape"]Output
{"b": ["bat", "bee"], "a": ["ant", "ape"]}ExplanationEach list is sorted: bat before bee.
Example 2
Input
words = ["cow", "Cat", "car"]Output
{"c": ["car", "Cat", "cow"]}ExplanationCase is ignored: car < cat < cow.
Example 3
Input
words = ["ant", "Ape", "Ant"]Output
{"a": ["ant", "Ant", "Ape"]}Explanation"ant" and "Ant" tie; "ant" came first.
Constraints
wordshas 0 to 50 words.- Each word has 1 to 20 English letters, and may have capitals.
Submit also runs 8 more tests you can't see.
Practises Dictionaries (lesson 11).
- A word's key is its first letter in lower case,
word[0].lower(), so"Bee"and"bat"share the key"b". groups.setdefault(letter, []).append(word)adds a word to its letter's list, making an empty list first when the letter is new.- Sort each list once every word is in, with
group.sort(key=str.lower): it compares the words in lower case, so"bat"comes before"Bee"(a plain.sort()puts every capital first). Python's sort is stable, so words that tie, such as"Ant"and"ant", keep their order.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Was this challenge helpful?
Thanks!
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
Code
def group_words(words):
"""Group words by their first letter.
words: list of str, none of them empty; the list
may be empty
Returns: dict, lower-case first letter -> the list of
words starting with it, A to Z ignoring case
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.