Syllabus Lesson 32 of 239 · Data Structures
Data Structures

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())   # 11
Your turn

Given 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.

Spotted a problem in this lesson? Report it

Code · runs in your browser
Output