← Practice
πŸ“– Dictionariesdicts-word-counts
LessonΒ·difficulty 2/5Β·~12 min

Dicts: counting words

Dictionaries

A dictionary maps keys to values:

python
ages = {"Ada": 27, "Linus": 54}
ages["Ada"]                   # 27
ages["Grace"] = 105           # add a new key
"Linus" in ages               # True

You can iterate over a dict in three useful ways:

python
for key in ages:                  # keys
    ...
for value in ages.values():       # values
    ...
for key, value in ages.items():   # both
    ...

Your task

Write a function word_counts(words) that takes a list of strings and returns a dictionary mapping each word to the number of times it appears (case-sensitive β€” "Hi" and "hi" are different keys).

python
word_counts(["a", "b", "a", "a", "b", "c"])
# {"a": 3, "b": 2, "c": 1}

word_counts([])
# {}

Tests

  • basic
  • empty
  • single
  • case sens (hidden)

✦ Stuck? Ask for a spark

warming up
Loading editor…

$ Console output will appear here.

>_AI tutor
Sign in to chat with the tutor.