50 XP

25. Group words by first letter

Intermediate dictionaries sorting

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", because a comes before e.
  • Words that differ only in case, such as "Ant" and "ant", keep the order they have in words. A word given twice is kept twice.
  • If words is empty, return an empty dictionary {}.

The order of the keys doesn't matter.

Example 1

Inputwords = ["bee", "ant", "bat", "ape"]
Output{"b": ["bat", "bee"], "a": ["ant", "ape"]}
ExplanationEach list is sorted: bat before bee.

Example 2

Inputwords = ["cow", "Cat", "car"]
Output{"c": ["car", "Cat", "cow"]}
ExplanationCase is ignored: car < cat < cow.

Example 3

Inputwords = ["ant", "Ape", "Ant"]
Output{"a": ["ant", "Ant", "Ape"]}
Explanation"ant" and "Ant" tie; "ant" came first.

Constraints

  • words has 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).

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