>_Code Club
← All exercises

python

Dictionaries

A dictionary stores pairs of key: value, like a real dictionary stores word: definition.

ages = {"Sam": 12, "Ada": 14}

print(ages["Ada"])        # 14
ages["Leo"] = 9           # add a new pair
ages["Sam"] = ages["Sam"] + 1   # Sam had a birthday

print("Ada" in ages)      # True

for name, age in ages.items():
    print(name, "is", age)

Your mission

Write count_letters(word) that returns a dictionary saying how many times each letter appears.

count_letters("hello")
# {"h": 1, "e": 1, "l": 2, "o": 1}

Hint: for each letter, if it's already in the dictionary add 1, otherwise set it to 1.

Next exerciseFizzBuzz →
Loading the editor…