How to use dictionaries
Create and read a dictionary
A dictionary maps unique hashable keys to values. Modern Python preserves insertion order, but keys should describe lookup meaning rather than position.
student = {"name": "Ada", "score": 95}
print(student["name"])
print(student.get("grade", "not assigned"))
Add and update values
Assignment adds a missing key or replaces an existing value. update() can merge several entries.
student = {"name": "Ada"}
student["score"] = 95
student.update({"active": True, "level": 2})
print(student)
Remove safely
pop() removes a key and returns its value. A default prevents KeyError when the key is absent.
settings = {"theme": "dark", "sound": True}
theme = settings.pop("theme")
missing = settings.pop("language", "English")
print(theme, missing, settings)
Iterate through entries
Iterating a dictionary alone yields keys. Use items() when both keys and values are needed.
prices = {"apple": 1.20, "banana": 0.75}
for item, price in prices.items():
print(f"{item}: ${price:.2f}")