← Python from Scratch Lesson 41 of 78 · 10 XP

Dictionaries

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

A dictionary (dict) holds key → value pairs. A value is found by its key instantly:

phone = {"Anya": "+77010000001", "Borya": "+77010000002"}
phone["Anya"]             # '+77010000001'
phone["Vika"] = "+7701…"  # add or change
del phone["Borya"]        # delete
"Anya" in phone           # True — checking for a key

If the key isn't there, phone["Gosha"] raises a KeyError. The safe option is get with a default value:

phone.get("Gosha", "no number")

Looping:

for name in phone:                 # the keys
    ...
for name, number in phone.items(): # the pairs
    print(name, number)

A classic task is counting: how many times each word appears.

counts = {}
for w in ["a", "b", "a"]:
    counts[w] = counts.get(w, 0) + 1
# {'a': 2, 'b': 1}

Task. Write a function count_words(text) that returns a dictionary "word → how many times it appeared". Words are separated by spaces; ignore case: "Cat cat" → {'cat': 2}.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.