- This topic is empty.
-
AuthorPosts
-
March 17, 2026 at 1:17 am #6206
When working with dictionaries in Python, a small mistake can break your entire program.
Letβs understand this with a real example from a PhoneBook app π
β The Problem
def get_entry(self, name: str): return self.__persons[name]Looks fine, right?
But what if the name doesnβt exist?
π Example:
phonebook = PhoneBook() phonebook.get_entry("Eric")π₯ Output:
KeyError: 'Eric'Your program crashes.
π€ Why Does This Happen?
Because:
self.__persons[name]means:
βGive me the value for this key β no matter what.β
If the key doesnβt exist β Python throws a KeyError
β The Safe Approach
def get_entry(self, name: str): if name not in self.__persons: return None return self.__persons[name]Now the behavior is:
Case Result Name exists Person object Name missing None
π‘ Even Better (Pythonic Way)
def get_entry(self, name: str): return self.__persons.get(name)π
.get()automatically returnsNoneif the key is missing.
π― Why This Matters
Instead of crashing, your program can now handle missing data:
person = phonebook.get_entry("Emily") if person is None: print("number unknown")β No crash
β Better user experience
β Cleaner code
π§ Key Concept: Defensive Programming
Always ask:
βWhat if the data is missing?β
Handling that case = professional coding.
π₯ Pro Tip
- Use
dict[key]β when you are 100% sure key exists - Use
dict.get(key)β when key might be missing
π¬ If you’re learning Python, this one concept will save you HOURS of debugging.
#Python #Programming #OOP #CodingTips #LearnToCode
- Use
-
AuthorPosts
- You must be logged in to reply to this topic.
