Project: my little dictionary
Section 10: Dictionaries (dict)Lesson 10.2 · ⏱ 10 min
🎯 Project goal
A little English–Spanish dictionary: we give it words and it translates the ones it knows, and says the others are not in it.
The idea: the key is the English word, and the value is its translation. Before we read any word we ask if w in words so no error appears.
words = {
"robot": "robot",
"sun": "sol",
"book": "libro",
"water": "agua",
}
for w in ["sun", "book", "cat"]:
if w in words:
print(w, "=", words[w])
else:
print(w, "= ? (not in my dictionary)")
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗sun = sol book = libro cat = ? (not in my dictionary)

- Add five more words to the dictionary.
- Make the program count the words it didn't find, and print the number at the end.
📌 Another example: a dictionary that learns
If it doesn't know the word, it asks for its meaning and saves it.
When the program asks, we type: star, then estrella.
words = {"sun": "sol", "moon": "luna"}
w = input("Word: ")
if w in words:
print(words[w])
else:
meaning = input("I don't know it. Meaning? ")
words[w] = meaning
print("Saved:", w, "=", words[w])
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗Word: star I don't know it. Meaning? estrella Saved: star = estrella
✍️ Practise
Add the word cat to the dictionary, then run the program again and notice the difference.
✍️ Practise here in the lesson✖ Close the labor open the lab in a new page ↗
🎯 Challenge yourself
Easy
Print all the words and their meanings (items).
👀 Show the solution🙈 Hide the solution
words = {"cat": "gato", "dog": "perro"}
for en, es in words.items():
print(en, "=", es)
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗cat = gato dog = perro
Result: cat = gato, dog = perro
Medium
Ask for a word 3 times, and say “I don't know it” if it isn't there.
👀 Show the solution🙈 Hide the solution
When the program asks, we type: cat, then lion, then dog.
words = {"cat": "gato", "dog": "perro"}
for i in range(3):
w = input("Word: ")
print(words.get(w, "I don't know it"))
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗Word: cat gato Word: lion I don't know it Word: dog perro
Result: gato, then I don't know it, then perro
Hard
A dictionary the other way round: from Spanish to English.
👀 Show the solution🙈 Hide the solution
words = {"cat": "gato", "dog": "perro", "sun": "sol"}
back = {}
for en, es in words.items():
back[es] = en
print(back["sol"])
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗sun
Result: sun

