๐Ÿ 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().