Changing a dict (update, setdefault, pop)
A dict can be changed in place: update merges in new keys, setdefault sets a value only if the key is missing, and pop removes a key and hands it back.
Used in 13 lessons of the course, from 01.05.
A dict is mutable: its methods change it in place, without building a new one.
d.update(other)copies the keys ofotherintod. If a key already existed, the new value wins.d.setdefault(key, value)returnsd[key]. If the key is missing, it first creates it withvalue. That way you don't overwrite what was there.d.pop(key)removes the key and returns its value. Withd.pop(key, None)it doesn't fail when the key is missing.
These methods change the dict, and update returns None, so don't write d = d.update(...).
In the course you'll see handle.update(...) in lesson 01.05. There update is a method of another object, but it reads the same way: it changes what already exists instead of building something new.
config = {"model": "a"}
config.update({"temperature": 0})
Reach for it when: you want to adjust a dict that already exists: add options, set a default value, or take out a key you no longer need.
Examples
Common mistake
config = {"a": 1}
config = config.update({"b": 2})
print(config)Why: update changes the dict in place and returns None. Assigning the result throws your dict away.
How to write it: Call config.update({"b": 2}) without assigning.
Common mistake
config = {"a": 1}
config.pop("b")Why: pop without a default fails when the key doesn't exist.
How to write it: Use config.pop("b", None) or check first with in.
