COLLECTIONSChapter 5 · Collections
Dictionary methods
.get(key, default) reads a value without crashing when the key is missing. .keys(), .values() and .items() let you loop over a dictionary, and .items() gives you each key and value together. .update(other) merges another dict in, and .pop(key) removes an entry and returns its value.
Worked example
How it reads
.get("color", "unknown")falls back to the default instead of raising KeyError.updateadds new keys and overwrites existing onesfor key, value in star.items()unpacks each pair
Common mistakes
d["missing"]raises KeyError. Used.get("missing")when a key might not be there.- Adding or removing keys while looping over the same dict raises RuntimeError. Loop over
list(d.items())instead.

Cloud tip: Counting things?
counts[word] = counts.get(word, 0) + 1 is the classic one-liner.

