🔄 Quick Recap (Day 9)
You mastered tuples: immutable, ordered sequences.
You used methods like
count(),index(), and unpacking for quick assignment.
🎯 What You’ll Learn Today
What a dictionary is and why it’s useful.
How to create a dictionary with key-value pairs.
How to access, add, modify, and remove entries.
Common dictionary methods:
keys(),values(), anditems().
📖 What Is a Dictionary?
A dictionary is like a real-life dictionary: you look up a word (key) to find its definition (value). In Python, dictionaries store data in key:value pairs, letting you quickly retrieve values by their keys.
Unordered: items don’t have a fixed position.
Mutable: you can change contents after creation.
Creating a Dictionary
Use curly braces {} with key: value entries separated by commas:
# Create a simple phonebook
directory = {
"Alice": "555-1234",
"Bob": "555-5678",
"Charlie": "555-9012"
}
print(directory)Output:
{'Alice': '555-1234', 'Bob': '555-5678', 'Charlie': '555-9012'}📖 Accessing and Modifying Entries
Access by Key
Retrieve a value by its key:
print(directory["Alice"]) # 555-1234Asking for a non-existent key raises a KeyError. To avoid this, use get():
print(directory.get("Eve", "Not found")) # Not foundAdding or Changing Entries
Assign a value to a new or existing key:
directory["Dave"] = "555-3456" # adds new entry
directory["Alice"] = "555-0000" # updates existing number
print(directory)Removing Entries
pop(key): removes and returns the value forkey.popitem(): removes and returns the last inserted pair.del: deletes by key without returning.
number = directory.pop("Bob")
print("Removed Bob's number:", number)
del directory["Charlie"]
print(directory)📖 Dictionary Methods
Use these to inspect contents:
keys(): returns a view of all keys.values(): returns a view of all values.items(): returns a view of(key, value)pairs.
print(directory.keys()) # dict_keys([...])
print(directory.values()) # dict_values([...])
print(directory.items()) # dict_items([(...), ...])🧙♂️ Take the Wand and Try Yourself
Create a file named
dict_practice.py.Inside, define a dictionary
student_scoreswith at least three names and their exam scores (numbers).Print the score for one student by key lookup.
Add a new student and score.
Update one student’s score.
Remove a student using
pop()and print their name and score.Print all student names using
keys(), and all scores usingvalues().
Solution Example (dict_practice.py):
# dict_practice.py
student_scores = {
"Alice": 85,
"Bob": 92,
"Charlie": 78
}
# Access
print("Alice's score:", student_scores["Alice"])
# Add
student_scores["Dave"] = 88
# Update
student_scores["Bob"] = 95
# Remove
removed_score = student_scores.pop("Charlie")
print("Removed Charlie with score", removed_score)
# Keys and values
print("Students:", student_scores.keys())
print("Scores:", student_scores.values())Expected output:
Alice's score: 85
Removed Charlie with score 78
Students: dict_keys(['Alice', 'Bob', 'Dave'])
Scores: dict_values([85, 95, 88])Run:
python dict_practice.pyOnce your output matches, you’ve mastered Python dictionaries!
Up next: Day 11: Object-Oriented Programming Basics — start building your own types.