Update, remove, look up with defaults, copy and build dictionaries with their built-in methods.
# update multiple items
person = {"name": "Alice"}
person.update({"age": 25, "city": "NYC"})
# ans: {"name": "Alice", "age": 25, "city": "NYC"}
# remove and return value
person = {"name": "Alice", "age": 25}
age = person.pop("age")
# ans: age is 25
# ans: person is {"name": "Alice"}
# remove and return last item
person = {"name": "Alice", "age": 25}
item = person.popitem()
# ans: item is ("age", 25)
"Last" means the most recently inserted pair: dictionaries remember insertion order.
# get or set default
person = {"name": "Alice"}
age = person.setdefault("age", 0)
# ans: age is 0
# ans: person is {"name": "Alice", "age": 0}
# remove all items
person = {"name": "Alice", "age": 25}
person.clear()
# ans: {}
# shallow copy
person = {"name": "Alice"}
person_copy = person.copy()
# ans: person_copy is {"name": "Alice"}
A new dictionary: adding keys to one does not affect the other. (Exercise 7 shows the catch.)
# create dict from keys
keys = ["a", "b", "c"]
d = dict.fromkeys(keys, 0)
# ans: {"a": 0, "b": 0, "c": 0}
Predict the result, then reveal it.
# update behavior?
d = {"a": 1}
d.update({"b": 2, "a": 10})
# ans: {"a": 10, "b": 2}
# pop with default?
d = {"a": 1}
d.pop("b", 0)
# ans: 0
# pop without default?
d = {"a": 1}
d.pop("b")
# ans: KeyError
# setdefault existing key?
d = {"a": 1}
d.setdefault("a", 10)
# ans: 1 (doesn't change existing)
# popitem on empty?
d = {}
d.popitem()
# ans: KeyError
# fromkeys default?
keys = ["a", "b"]
d = dict.fromkeys(keys)
# ans: {"a": None, "b": None}
# copy is shallow?
d = {"a": [1, 2]}
d2 = d.copy()
d2["a"].append(3)
# ans: d is {"a": [1, 2, 3]}
# clear return?
d = {"a": 1}
result = d.clear()
# ans: result is None
# ans: d is {}
# update from pairs?
d = {"a": 1}
d.update([("b", 2), ("c", 3)])
# ans: {"a": 1, "b": 2, "c": 3}
# multiple setdefault?
d = {}
d.setdefault("a", []).append(1)
d.setdefault("a", []).append(2)
# ans: {"a": [1, 2]}
The first call stores a new empty list and returns it; the second finds that same list and returns it. A handy way to group values.
updateAdds or overwrites many pairs, from a dict or a list of pairs.
pop / popitemRemove and return; a missing key (or an empty dict) raises KeyError unless pop has a default.
setdefaultReturns the value if the key exists, otherwise stores and returns the default.
clear / copy / fromkeysclear returns None; copy is shallow; fromkeys defaults every value to None.