← All posts
postMay 13, 2026
Count word frequencies in a sentence
#python#challenge#beginner
Easy⏱️ Logic Challenge
Given a sentence, return a dictionary mapping each word to how many times it appears. Example input: "data is the new data". Expected: {"data": 2, "is": 1, "the": 1, "new": 1}
Ver solución
def count_words(sentence):
counts = {}
for word in sentence.split():
counts[word] = counts.get(word, 0) + 1
return counts
print(count_words("data is the new data"))
# {'data': 2, 'is': 1, 'the': 1, 'new': 1}
Word counting is the simplest form of text analytics. The pattern of splitting input, iterating, and aggregating into a dictionary appears in almost every data pipeline you will ever build — counting log lines, tallying records by category, computing distinct values.
Solve it with two tools: split() to break the string into words, and a dictionary to accumulate counts. The exact same pattern scales to processing millions of rows in Pandas or PySpark.