Editor

Safe Access with get()

Beginner · Write the code · from Python Dictionaries: The Complete Guide with Real Examples

From the lesson: Python Dictionaries: The Complete Guide with Real Examples

Open the contacts app on your phone. You look up a person by name and get their phone number. You don't search by position - you don't say "give me contact number 47." You search by name.

Read the lesson

A user profile dictionary is given. Use the .get() method to safely print the user's phone number. If the key 'phone' doesn't exist, print 'No phone number'.

Expected output:

No phone number
profile = {'name': 'Alice', 'email': 'alice@mail.com'}
# Use .get() to safely access the phone key

More Dictionaries exercises

All Python exercises · 50 practice problems · Data Structures quiz