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 lessonA 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 numberprofile = {'name': 'Alice', 'email': 'alice@mail.com'}
# Use .get() to safely access the phone key
More Dictionaries exercises
- Create a Dictionary and Access a ValueBeginner
- Add and Modify Dictionary EntriesBeginner
- Loop Through a DictionaryBeginner
- Predict the Output: Duplicate KeysBeginner
- Fix the Bug: Checking for a ValueIntermediate
- Build a Word CounterIntermediate
- Access Nested Dictionary DataIntermediate
All Python exercises · 50 practice problems · Data Structures quiz