
ValueError Why? Because I did this:
print(student['marks'])
And guess what? 'marks' key was missing.
-
Use
.get()Like a Gentleman
❌ Wrong Way
marks = student['marks']
✅ Right Way:
marks = student.get('marks', 0)
Now if 'marks' doesn’t exist — you get 0. No drama. No crying. Just calm
- Use
defaultdict— Python magic
Tired of checking if key exists before adding?
Try this:
from collections import defaultdict
student_scores = defaultdict(list)
student_scores['Azeem Teli'].append(95)
No need to check if it 'Azeem Teli' exists. Python will auto-create it for you!
-
Loop Like a Pro with
.items()
You don’t need to juggle dict.keys() and dict.values() like a circus artist. Just do this:
for name, marks in student.items():
print(f"{name} scored {marks}")
Clean. Readable. Pythonic.
-
Use
.setdefault()for Lazy People 😴
This method is called the chef’s kiss for coders as lazy as me (😅)
student.setdefault('name', 'Unknown')
If 'name' exists — nothing changes. If not — it sets to 'Unknown'.
-
Because you are fancy Use Dictionary Comprehensions
Instead of:
squares = {}
for i in range(10):
squares[i] = i*i
Do this:
squares = {i: i*i for i in range(10)}
Looks cool. Runs cool. Boss move 😎
- Don’t Use
dictas a Variable Name!
I know… we all must have done this once
dict = {'a': 1}
Bro, you just overwrote Python’s own dict() function.
RIP to built-ins
