Dict Methods and Iterating
The safe way to read a possibly-missing key is .get(). It returns None (or a default you choose) instead of raising an error:
person = {"name": "Ada"}
print(person.get("name")) # Ada
print(person.get("email")) # None
print(person.get("email", "-")) # -.setdefault(key, default) returns the value if the key exists, otherwise it inserts the default and returns that:
scores = {}
scores.setdefault("sam", 0)
print(scores) # {'sam': 0}To loop over a dict you usually want the pairs. .items() gives you both key and value:
prices = {"pen": 2, "book": 9}
for name, cost in prices.items():
print(name, cost)
# pen 2
# book 9.keys() gives just the keys and .values() gives just the values. Summing values is common:
total = sum(prices.values()) # 11Given prices = {"pen": 2, "book": 9, "bag": 14}, compute total as the sum of all values. Then use .get() to look up "hat" with a default of 0 and store it in hat_price.
This lesson is locked
Lessons open one at a time. Finish the previous lesson to unlock this one.