Python by Projects

unit

Word Wizard

A WORD WIZARD translates a word in a blink and counts how often each word appears. Its magic is a dictionary — pairs of keys and values. Each idea comes as a short ladder (simplest → one step up → real use) with a Notice naming the one new thing.

You will learn

  • Build a dictionary that pairs each key with a value.
  • Look up a value with [] or the safe .get(), and add or change a pair.
  • Walk a dictionary's keys, or its key-value pairs with .items().
  • Count how often each word appears in a list.

Lesson 1: Build the Wizard's Phrasebook

A dictionary (dict) pairs each key with a value. Curly braces hold the pairs; a colon joins each key to its value.

translations = {"hello": "hola"}
print(translations)

Output

{'hello': 'hola'}

Notice

One pair — the key "hello" maps to the value "hola".

translations = {"hello": "hola", "cat": "gato"}
print(translations)

Output

{'hello': 'hola', 'cat': 'gato'}

Notice

Separate more pairs with commas.

translations = {"hello": "hola", "cat": "gato", "dog": "perro"}
print(translations)

Output

{'hello': 'hola', 'cat': 'gato', 'dog': 'perro'}

Notice

A dict can hold as many key→value pairs as you need — the wizard's phrasebook.

To look up a value, put its key in square brackets.

translations = {"hello": "hola", "cat": "gato", "dog": "perro"}
print(translations["hello"])

Output

hola

Notice

translations["hello"] returns that key's value, "hola".

translations["bird"] = "pajaro"
print(translations)

Output

{'hello': 'hola', 'cat': 'gato', 'dog': 'perro', 'bird': 'pajaro'}

Notice

Assign to a new key to ADD a pair (or to an existing key to change its value).

print(translations.get("fish", "???"))

Output

???

Notice

.get(key, default) returns the value, or the default ("???") when the key is missing — no crash.

Why .get? A missing key in square brackets CRASHES. Here is the deliberate bug — leave it unrun and read the traceback from the bottom.

Read the error

translations = {"hello": "hola", "cat": "gato"}
translations["fish"]

KeyError: 'fish' means the key is not in the dictionary. .get() exists precisely to avoid this when a word might be missing. (Search words also arrive messy; raw.strip().lower() cleans them to match the tidy lowercase keys.)

Lesson 2: Walk the Phrasebook

A for loop can walk a dictionary. Looping over the dict gives one KEY per trip.

translations = {"hello": "hola", "cat": "gato", "dog": "perro"}
for word in translations:
    print(word)

Output

hello
cat
dog

Notice

Looping over a dict visits its keys, one per trip.

translations = {"hello": "hola", "cat": "gato", "dog": "perro"}
for word, translation in translations.items():
    print(f"{word} means {translation}")

Output

hello means hola
cat means gato
dog means perro

Notice

.items() gives the key AND value together on each trip.

translations = {"hello": "hola", "cat": "gato", "dog": "perro"}
word_count = 0
for word, translation in translations.items():
    word_count = word_count + 1
print(f"The phrasebook knows {word_count} words.")

Output

The phrasebook knows 3 words.

Notice

Looping the pairs lets you compute over the whole dictionary — here, counting its entries.

Put it together: wrap .get in a translate helper, then loop a whole list of words through it — a missing word gets the friendly default.

def translate(word, dictionary):
    return dictionary.get(word, "???")


translations = {"hello": "hola", "cat": "gato", "dog": "perro", "bird": "pajaro"}
words_to_translate = ["hello", "bird", "fish"]
for word in words_to_translate:
    print(f"{word} means {translate(word, translations)}")

Output

hello means hola
bird means pajaro
fish means ???

Try it yourself

def translate(word, dictionary):
    return dictionary.get(word, "???")


translations = {"hello": "hola", "cat": "gato", "dog": "perro", "bird": "pajaro"}
words_to_translate = [input("Word 1? "), input("Word 2? "), input("Word 3? ")]
for word in words_to_translate:
    print(f"{word} means {translate(word, translations)}")

Notice

(It reads live input, so it does not run here.)

Lesson 3: Count the Word Log

A spell-checker notices repeated words. Start with an empty dict counts, then one loop over the list: a seen word grows by 1; a first sighting begins at 1.

words = ["cat", "dog", "cat", "bird", "cat"]
counts = {}
for word in words:
    if word in counts:
        counts[word] = counts[word] + 1
    else:
        counts[word] = 1
print(counts)

Output

{'cat': 3, 'dog': 1, 'bird': 1}

Notice

if word in counts chooses between growing a count and starting a new one at 1.

counts = {"cat": 3, "dog": 1, "bird": 1}
for word, count in counts.items():
    label = word + " => " + str(count)
    print(label)

Output

cat => 3
dog => 1
bird => 1

Notice

Walk the pairs with .items() and build a label; str(count) turns the number into text so + can join it.

counts = {"cat": 3, "dog": 1, "bird": 1}
best_word = ""
best_count = 0
for word, count in counts.items():
    if count > best_count:
        best_count = count
        best_word = word
print(f"Most common word: {best_word} ({best_count})")

Output

Most common word: cat (3)

Notice

Track the best-so-far count while looping to find the most common word.

Try it yourself

words = [input("Word 1? "), input("Word 2? "), input("Word 3? "), input("Word 4? "), input("Word 5? ")]
counts = {}
for word in words:
    if word in counts:
        counts[word] = counts[word] + 1
    else:
        counts[word] = 1
print(counts)

Notice

(It reads live input, so it does not run here.)

Trade word logs with a partner: count each other's lists and name the most common word. Why must counts be reset to {} before re-counting a grown list?

Recap

  • {"hello": "hola"} pairs a key with its value, and d[key] = value adds or updates a pair.
  • A missing key in square brackets raises a KeyError; .get(key, default) returns the default instead.
  • Looping over a dictionary gives its keys, and .items() gives each key with its value.
  • To count words, start with {}; if word in counts, add 1, otherwise begin it at 1.

You can now build a phrasebook that translates and a counter that finds the most common word.

Go to the exercises (23)

For parents and teachers: report a problem