17
Dictionaries
Dictionaries: Look Up Data by Key, Not Position
What You Might Be Wondering
"When do I use a list vs. a dict?"
If you access data by position, use a list. If you access data by field name (name/email/age), use a dict.
One-Line Definition
A dictionary is a key-value mapping structure, perfect for organizing structured data.
Real-Life Analogy
A dict is like a contact book: you look up someone's phone number (value) by their name (key), not by what row they're on.
Minimal Working Example
user = {
"name": "Alice",
"age": 25,
"city": "Sydney",
}
print(user["name"]) # Alice
Reading & Updating
print(user.get("email")) # None
user["age"] = 26
user["email"] = "a@example.com"
Deleting & Iterating
user.pop("city")
for k, v in user.items():
print(k, v)
Real Example: Word Frequency Count
text = "python ai python"
counter = {}
for w in text.split():
counter[w] = counter.get(w, 0) + 1
print(counter) # {'python': 2, 'ai': 1}
Quick Quiz (5 min)
- Build a student grades dict.
- Print each student's name and score.
- Find and output the top-scoring student.
Quiz Rubric & Grading Criteria
- Direction: write runnable code that covers the core requirements and edge cases from the prompt.
- Criterion 1 (Correctness): main flow produces correct results, key branches execute.
- Criterion 2 (Readability): clear variable names, no excessive nesting.
- Criterion 3 (Robustness): basic protection against empty values, type errors, or unexpected input.
Take-Home Task
Organize a "user registration form" as a dict, then validate that all required fields exist.
Acceptance Criteria
You can independently:
- Create, read, update, and delete dict entries
- Use
get()for safe reads - Use a dict to accumulate counts
Common Errors & Debugging Steps (Beginner Edition)
- Error message looks like gibberish: read the last line for the error type (
TypeError,NameError, etc.), then trace back to the offending line. - Not sure what a variable holds: drop a temporary
print(variable, type(variable))to check. - Changed code but nothing happened: make sure you saved the file, you're running the right file, and your terminal environment (venv) is correct.
Common Misconceptions
-
Misconception:
dict[key]is always safe. -
Reality: if the key doesn't exist, it throws a
KeyError. Useget()when you're not sure. -
Misconception: you can use lists or dicts as keys.
-
Reality: keys must be hashable (typically
str,int, ortuple).