🐍 Lesson 9: Dictionaries

Match keys to values, like words to meanings

← Back to Python Basics

📒 What is a dictionary?

A dictionary stores pairs of keys and values. Instead of looking things up by position (like a list), you look them up by a name (the key). Just like a real dictionary: you look up a word (key) to find its meaning (value).

player = { "name": "Maya", "level": 7, "health": 100 }

Curly braces { }, and each pair is written as key: value.

🔑 Looking up a value

Use the key in square brackets:

print(player["name"]) # Maya print(player["level"]) # 7

✏️ Adding and changing

player["level"] = 8 # change a value player["score"] = 250 # add a brand-new pair print(player)

🔍 Safe lookups with .get()

Missing keys cause errors

Asking for a key that doesn't exist (player["age"]) crashes the program. Use .get() to avoid that — it returns None (or a default) instead.

print(player.get("age")) # None (no crash) print(player.get("age", "unknown")) # unknown

🔁 Looping through a dictionary

prices = {"apple": 2, "banana": 1, "cherry": 5} for fruit in prices: print(f"{fruit} costs ${prices[fruit]}") # Or get both at once with .items() for fruit, price in prices.items(): print(f"{fruit}: {price}")

🛠️ Useful tools

prices = {"apple": 2, "banana": 1} print(prices.keys()) # the keys print(prices.values()) # the values print("apple" in prices) # True — is this key there? print(len(prices)) # 2 — how many pairs

✅ What you learned

  • Dictionaries store key → value pairs in { }.
  • Look up with dict["key"] or safely with .get().
  • Add or change with dict["key"] = value.
  • Loop with for k in dict or .items().