Lesson 3: in, .get() & iterating a dictionary
A direct lookup d[key] crashes if the key is missing. Here we learn safe, handy tools: in checks whether a key exists, .get() returns a value with a default, and a loop walks the keys, values, or pairs with .keys(), .values(), and .items().
Before opening a drawer, you ask "is there such a drawer?" (in). .get() is asking for a drawer and getting a polite "nothing" instead of a shout if it's missing. Iterating is going drawer by drawer.
- in
- An operator that checks whether a key exists in a dictionary, returning True or False.
- .get()
- A method that fetches a value by key, returning a default instead of an error if the key is missing.
- .items()
- A method that returns all key-value pairs, handy for looping.