Learn to code with step-by-step lessons. A place for students to work through programming fundamentals and build skills.
A dictionary stores key–value pairs. Like a real dictionary: you look up a word (the key) and get its meaning (the value).
In a real dictionary you have:
In Python we do the same: each key has one value.
Use curly braces. Each pair is "key": value:
glossary = {"cookie": "a baked snack", "variable": "a name for a value in code"}
So glossary["cookie"] gives "a baked snack".
Use the key in square brackets:
dictionary = {"cookie": "a baked snack"}
print(dictionary["cookie"]) # a baked snack
If the key doesn’t exist, you get an error. You can avoid that with .get(): dictionary.get("missing") returns None (or a default you choose).
dictionary["new_key"] = "new value"words = {"hello": "a greeting", "loop": "code that repeats", "bug": "an error in code"}
word = input("Enter a word: ")
if word in words:
print(words[word])
else:
print("Not in dictionary")
import random and random.choice(list(words.keys())) and ask “What does X mean?”)Next: 4.1 Defining functions — reusing code with functions.