PYTHON CORE · LESSON 45

The key may not be.

Method get in the dictionary · about 10 minutes

Learning with progressRead the summary for free. To save the work, log in to the account.
STEP 1

Careful search

The square brackets give an error if there is no key. get allows you to call a backup response.

book = {"title": "Космос"}
print(book.get("pages", 0))
Dictionary search
Key keypagesDictionaryno keyReserve.0

✦ There is no pages key, so 0 will appear.

STEP 2

When the key is

If the key is found, get will return the real value. You won't need a backup.

book = {"pages": 20}
print(book.get("pages", 0))

✦ Now there will be 20.

IN-CLASS PRACTICE

Type the code yourself

Reprint the spare value example.

game = {"score": 3}
print(game.get("lives", 0))
Open the editor for class work
HOMEWORK

Solve it yourself

Create book with a title key and a «Космос» value. Using get, output the value of the pages key, and if not, 0.

The answer is hidden. Use similar examples from the lesson notes.

Opening up your homework