3.2 Dictionaries and objects

Learn to code with step-by-step lessons. A place for students to work through programming fundamentals and build skills.

3.2 Dictionaries and objects

A dictionary stores key–value pairs. Like a real dictionary: you look up a word (the key) and get its meaning (the value).

Why “dictionary”?

In a real dictionary you have:

In Python we do the same: each key has one value.

Creating a dictionary

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".

Getting a value

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).

Adding and changing

Example: word lookup

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")

Mini project: Glossary quiz

  1. Make a dictionary of 5 programming words and their definitions.
  2. Use a loop to ask the user for a word.
  3. If the word is in the dictionary, print its definition; otherwise say “Unknown”.
  4. (Optional: pick a random key with import random and random.choice(list(words.keys())) and ask “What does X mean?”)

Next: 4.1 Defining functions — reusing code with functions.