Learning Goals
3 minBy the end of this lesson you can:
- Build a dictionary with curly braces and
key: valuepairs. - Read a value by its key with
d["name"]and update or add entries with assignment. - Check whether a key exists with the
inoperator — and use.get()to look up a key safely.
Warm-Up
5 minImagine a list of student details:
student = ["Aisyah", 12, "Kuala Lumpur", "art"]
What was at index 2 again? "Kuala Lumpur". And index 3? "art". You can't tell without a comment — the data has lost its labels.
What if we could say "the city" or "the subject" instead of "item 2" or "item 3"?
student = { "name": "Aisyah", "age": 12, "city": "Kuala Lumpur", "subject": "art", } print(student["city"]) print(student["subject"])
Show the answer
Kuala Lumpur art
Same four pieces of data, but every one now has a name. No more "what's at index 2 again?"
A dictionary stores pairs: a key (a label) and a value (the data). Look things up by name, not by position.
New Concept · The Dictionary
14 minBuilding one
Use curly braces { }. Each entry is key: value, entries separated by commas.
prices = { "nasi lemak": 8.00, "char kway teow": 9.50, "roti canai": 3.50, "cendol": 4.00, } empty = {} # an empty dictionary, ready to be filled
Keys are usually strings, but they can be numbers too. Values can be anything — strings, numbers, lists, even other dictionaries.
Reading by key
Same square brackets as lists — but with the key inside instead of an index:
print(prices["nasi lemak"]) # → 8.0 print(prices["roti canai"]) # → 3.5
Adding and updating
Assign to a new key — Python creates the entry. Assign to an existing key — Python updates it.
prices["milo"] = 4.50 # ← new entry prices["roti canai"] = 4.00 # ← update an existing one print(prices)
{'nasi lemak': 8.0, 'char kway teow': 9.5, 'roti canai': 4.0, 'cendol': 4.0, 'milo': 4.5}Removing
Use del or .pop(). .pop() returns the removed value, like with lists.
del prices["cendol"] gone = prices.pop("milo") print(gone) # → 4.5 print(prices)
The crash · missing keys
Look up a key that isn't there and Python explodes with KeyError:
print(prices["bubble tea"]) # KeyError: 'bubble tea'
Two ways to dodge it. Use in to check first:
if "bubble tea" in prices: print(prices["bubble tea"]) else: print("Not on the menu.")
Or use .get() — it returns None when the key is missing, or a default of your choice:
p1 = prices.get("bubble tea") print(p1) # → None p2 = prices.get("bubble tea", 0) print(p2) # → 0
Use d[key] when you expect the key — a missing key is a bug worth crashing for. Use .get(key, default) when the key is genuinely optional — a settings file, a missing high-score, a fresh user.
How many entries?
len() on a dictionary counts the number of pairs:
print(len(prices)) # → number of menu items
Worked Example · The Hawker Menu
12 minThe story
Pak Cik Razif's warung is opening tomorrow. He gives you a sheet of dishes and their prices, plus a few special requests:
- Build the menu in code, so the till can look prices up by dish name.
- Add a new dish — roti planta at RM 4.50 — after a customer asks for it.
- Update cendol to RM 5.00 because santan got expensive.
- The till sometimes asks for a dish that isn't on the menu. Print
Not on the menu.instead of crashing. - Tell Pak Cik how many items the menu has now.
Save as menu.py:
Code
# menu.py — Pak Cik Razif's menu, built with a dictionary menu = { "nasi lemak": 8.00, "char kway teow": 9.50, "roti canai": 3.50, "cendol": 4.00, } # Step 2 — new dish menu["roti planta"] = 4.50 # Step 3 — price update menu["cendol"] = 5.00 # Step 4 — safe lookups order = "nasi lemak" if order in menu: print(order, "— RM", menu[order]) else: print("Not on the menu.") # Try a missing one print(menu.get("bubble tea", "Not on the menu.")) # Step 5 — count print("Menu has", len(menu), "items.")
Output
nasi lemak — RM 8.0 Not on the menu. Menu has 5 items.
Read the diff
Look at the two ways we asked for a price. The first uses menu[order] after guarding with if order in menu. The second uses .get(...) with a fallback string. Both avoid the crash; choose by which feels clearer for the situation.
The variable that holds a dictionary is often named for the "by what" relationship. prices reads as "prices by dish". capitals reads as "capitals by country". ages reads as "ages by name". A good name tells the reader what the keys are without looking.
Try It Yourself
13 minThree exercises. Type, run, fix typos.
Build a dictionary capitals with four country/capital pairs: Malaysia/Kuala Lumpur, Indonesia/Jakarta, Thailand/Bangkok, Singapore/Singapore. Print the capital of Thailand.
Hint
capitals = { "Malaysia": "Kuala Lumpur", "Indonesia": "Jakarta", "Thailand": "Bangkok", "Singapore": "Singapore", } print(capitals["Thailand"]) # → Bangkok
Take the same capitals. Add Vietnam/Hanoi. Update Indonesia's capital to Nusantara (the planned new one). Print the whole dictionary and its length.
Hint
capitals["Vietnam"] = "Hanoi" capitals["Indonesia"] = "Nusantara" print(capitals) print("Total:", len(capitals))
Adding and updating use the same syntax — Python figures out which it is by whether the key already exists.
Ask the user for a country with input(). If it's in capitals, print the capital. Otherwise print Sorry, I don't know that country's capital. Use .get() with a default.
Hint
country = input("Country? ") capital = capitals.get(country, "Sorry, I don't know that country's capital.") print(capital)
One line for the lookup — no if, no else, no crash. That's the power of .get().
Mini-Challenge · The Personal Phonebook
8 minBuild phonebook.py, a tiny menu-driven contact list — but instead of a parallel-list mess, use a dictionary mapping name → phone number.
Inside a while True: loop, print a four-option menu and act on each choice:
1— add a contact (ask for name, then phone, store in the dict).2— look up a contact (ask for a name, use.get()with a default of"Not found.").3— list all contacts (loop and print eachname: phone).4— quit.
Stretch goal. Add option 5 — "delete a contact", using del after an in check.
Show one possible solution
# phonebook.py — a dictionary-backed contact list contacts = {} while True: print() print("1 add 2 lookup 3 list 4 quit 5 delete") choice = input("Choose: ") if choice == "1": name = input("Name : ") phone = input("Phone: ") contacts[name] = phone print("Saved.") elif choice == "2": name = input("Look up: ") print(contacts.get(name, "Not found.")) elif choice == "3": if len(contacts) == 0: print("Phonebook is empty.") else: for name in contacts: print(name, ":", contacts[name]) elif choice == "4": print("Bye!") break elif choice == "5": name = input("Delete: ") if name in contacts: del contacts[name] print("Removed.") else: print("That name isn't in the book.") else: print("Pick 1-5.")
Non-negotiables: a contacts = {} empty dict, the while True menu loop, contacts[name] = phone for adding, .get(name, "Not found.") for safe lookup, and a loop that prints each entry.
Recap
3 minA dictionary stores data as label → value pairs. Build it with curly braces, read with square-bracket key lookup, add or update with simple assignment, remove with del or .pop(). Use in or .get(key, default) for safe lookups — bare d[key] crashes on a missing key. len(d) counts the pairs. Once you start thinking in dictionaries, parallel lists feel clumsy in comparison.
Vocabulary Card
- dictionary (dict)
- An unordered collection of key → value pairs, written with curly braces.
- key
- The label used to find a value. Usually a string. Must be unique inside one dictionary.
- value
- The data stored under a key. Can be any type — strings, numbers, lists, even other dictionaries.
- .get(key, default)
- Safe lookup. Returns the value if the key is present, otherwise the default (or
None). - KeyError
- The crash you get when asking for a key that's not in the dictionary using bare
d[key].
Homework
4 minSave a new file stationery.py. Imagine you run the school's stationery shop. Build a dictionary stock mapping each item to how many you have left.
Your file must:
- Start with five items in
stock: pencil 50, eraser 30, ruler 12, sharpener 8, exercise book 20. - Print the current stock.
- Simulate three sales by reducing the matching value in the dict — sold 5 pencils, sold 2 rulers, sold 1 sharpener.
- Print the new stock and the total number of items still on the shelves (use
sum(stock.values())— a sneak peek at PY-L2-06). - Ask the user for an item with
input()and use.get(item, 0)to report how many are left.
Stretch. Add a new item — "highlighter" — with 15 in stock, then print only the items with fewer than 15 left using a for loop and an if.
Sample · stationery.py
# stationery.py — stock counts in a dictionary stock = { "pencil": 50, "eraser": 30, "ruler": 12, "sharpener": 8, "exercise book": 20, } print("Start :", stock) stock["pencil"] = stock["pencil"] - 5 stock["ruler"] = stock["ruler"] - 2 stock["sharpener"] = stock["sharpener"] - 1 print("Now :", stock) print("Items :", sum(stock.values())) want = input("Check stock for? ") print(want, "left:", stock.get(want, 0)) # Stretch stock["highlighter"] = 15 print("Low stock (< 15):") for item in stock: if stock[item] < 15: print(" -", item, ":", stock[item])
Non-negotiables: the five-item starting dict, three subtractions for sales, a sum(stock.values()) total, and one safe .get(..., 0) lookup.