50 XP

14. Word frequency

Intermediate dictionaries strings

Write a function word_counts(text) that takes a string text and returns a dictionary (a dict) that maps each word to the number of times it appears in text.

  • Words are separated by spaces. There can be more than one space between words, and spaces at the start or end.
  • Capitals don't matter: The, the and THE are all the word "the". Use the words in lower case as the keys.
  • If text is empty, return an empty dictionary {}.

The order of the keys doesn't matter.

Example 1

Inputtext = "the cat and the hat"
Output{"the": 2, "cat": 1, "and": 1, "hat": 1}
Explanation"the" appears twice, every other word once.

Example 2

Inputtext = "Go go GO"
Output{"go": 3}
ExplanationIn lower case, all three are "go".

Example 3

Inputtext = ""
Output{}
ExplanationNo words, so the dictionary is empty.

Constraints

  • text has 0 to 100 characters.
  • It holds only letters and spaces.

Submit also runs 4 more tests you can't see.

Practises Dictionaries (lesson 11).

Code
def word_counts(text):
    """Count how many times each word appears.

    text: str, words separated by spaces; may be empty
    Returns: dict, each word in lower case -> its count
    """
    # Write your code here
    pass