Phase 2 — Collections
get, keys, values & items
The methods you'll use to safely read and loop over a dict
get — safe access
.get() reads a key without raising an error if it's missing.
user = {"id": 1, "name": "John"}
user.get("name") # "John"
user.get("phone") # None
user.get("phone", "N/A") # "N/A" — a default value if the key is missingThis is basically Python's version of JS's ?? fallback:
user.phone ?? 'N/A';Prefer .get() over user["key"] whenever the key might not exist.
keys — just the keys
user = {"id": 1, "name": "John"}
print(user.keys()) # dict_keys(['id', 'name'])Same as JS's Object.keys(user).
values — just the values
print(user.values()) # dict_values([1, 'John'])Same as JS's Object.values(user).
items — key and value together
.items() is what you'll use most, especially in a for loop:
for key, value in user.items():
print(key, value)id 1
name JohnThis is the same shape as JS's Object.entries(user) combined with array destructuring:
for (const [key, value] of Object.entries(user)) {
console.log(key, value);
}