A profile can change a city and remove an outdated phone number.
What You Need to Understand
Dictionaries support reading with [] or get(), updating existing keys by assignment, adding new keys, and deleting keys with del or pop(). Choose the operation based on missing-key behavior.
When to Use It
A profile can change a city and remove an outdated phone number.
Step-by-Step Python Example
profile = {"name": "Noa", "city": "Tel Aviv", "phone": "123"}
profile["city"] = "Haifa"
profile["email"] = "[email protected]"
removed_phone = profile.pop("phone", None)
print(removed_phone)
print(profile)
How the Example Works
Assigning to city updates it, email adds a key, and pop() removes phone while returning its previous value.
Example Output
123
{'name': 'Noa', 'city': 'Haifa', 'email': '[email protected]'}
none
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
record = {"qty": 5}
record["qty"] += 1
print(record.pop("note", "none"))
Important Behavior and Edge Cases
Using del profile["missing"] raises KeyError. A supplied pop() default avoids it when absence is expected.
Try It Yourself
Update a stock quantity and safely remove an optional field.
Common Beginner Mistakes
- Using
del profile["missing"]raisesKeyError. A suppliedpop()default avoids it when absence is expected. - Treating missing dictionary keys, replacement precedence, and shallow copies as if they had identical behavior in every context.
Key Takeaways
- Dictionaries support reading with
[]orget(), updating existing keys by assignment, adding new keys, and deleting keys withdelorpop(). - Assigning to
cityupdates it,emailadds a key, andpop()removesphonewhile returning its previous value. - Using
del profile["missing"]raisesKeyError.