A classroom program maps a student ID to a current score.
What You Need to Understand
A dictionary maps unique hashable keys to associated values. It preserves insertion order and allows values of any type. Each key refers to one current value.
When to Use It
A classroom program maps a student ID to a current score.
Step-by-Step Python Example
scores = {"S101": 84, "S102": 92}
print(scores["S101"])
scores["S101"] = 88
scores["S103"] = 75
print(scores)
How the Example Works
Updating an existing key replaces its value; assigning a new key adds a mapping.
Example Output
84
{'S101': 88, 'S102': 92, 'S103': 75}
{'pen': 6}
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
stock = {"pen": 4}
stock["pen"] += 2
print(stock)
Important Behavior and Edge Cases
Repeated keys in a dictionary literal do not create multiple entries: the last value wins. Missing-key direct lookups raise KeyError.
Try It Yourself
Create a dictionary for a product with its name and quantity, then increase the quantity.
Common Beginner Mistakes
- Repeated keys in a dictionary literal do not create multiple entries: the last value wins. Missing-key direct lookups raise
KeyError. - Treating missing dictionary keys, replacement precedence, and shallow copies as if they had identical behavior in every context.
Key Takeaways
- A dictionary maps unique hashable keys to associated values.
- Updating an existing key replaces its value; assigning a new key adds a mapping.
- Repeated keys in a dictionary literal do not create multiple entries: the last value wins.