Day 7: Dictionaries in Python – The Ultimate Key-Value Powerhouse!
Day 7: Dictionaries in Python – The Ultimate Key-Value Powerhouse!
Heyy, Day 7 is here! You’ve already crushed Hello World, Variables, Operators, Strings, Lists, Tuples, and Sets. Now, Day 7 is all about Dictionaries – one of the most powerful and most used data structures in Python!
Think of it like a real dictionary:
Word → Meaning Name → Phone Number Roll No → Marks
In Python, it’s Key → Value pairs. Super fast, super clean, and super useful!
What is a Dictionary? (10 mins)
student = {
"name": "Middle class blog",
"age": 22,
"grade": "A+",
"is_pass": True
}- Uses curly braces {}
- Format: "key": value
- Keys must be unique (if duplicate, last one wins)
- Values can be anything: string, int, list, even another dict!
Accessing Values:
print(student["name"]) # Ravi
print(student.get("age")) # 22 (safe – returns None if key missing)Must-Know Dictionary Methods (15 mins)
| Method | What it does | Example |
|---|---|---|
| .keys() | Returns all keys | student.keys() → dict_keys(['name', 'age', ...]) |
| .values() | Returns all values | student.values() |
| .items() | Returns (key, value) pairs | student.items() |
| .update() | Merge another dict | student.update({"city": "Hyderabad"}) |
| .pop("key") | Remove a key | student.pop("grade") |
Try This:
car = {"brand": "Toyota", "model": "Camry", "year": 2023}
print("Keys:", list(car.keys()))
print("Values:", list(car.values()))
# Add new key-value
car["color"] = "Red"
car.update({"price": 30000})
print(car)Output:
Keys: ['brand', 'model', 'year']
Values: ['Toyota', 'Camry', 2023]
{'brand': 'Toyota', 'model': 'Camry', 'year': 2023, 'color': 'Red', 'price': 30000}Mini Project: Student Grade Book (30–40 mins)
Let’s build a Student Grade Book! It will:
- Take student name
- Take 3 subject marks
- Calculate average
- Assign grade
- Print a clean report
Code (day7_gradebook.py):
# Student Grade Book
print("=== Student Grade Book ===")
name = input("Student name: ")
# Input marks
sub1 = float(input("Maths: "))
sub2 = float(input("Science: "))
sub3 = float(input("English: "))
# Store in dictionary
student = {
"name": name,
"marks": [sub1, sub2, sub3],
"total": sub1 + sub2 + sub3,
"average": round((sub1 + sub2 + sub3) / 3, 2)
}
# Grade logic
avg = student["average"]
if avg >= 90:
grade = "A+"
elif avg >= 80:
grade = "A"
elif avg >= 70:
grade = "B"
elif avg >= 60:
grade = "C"
else:
grade = "Fail"
student["grade"] = grade
# Print Report
print("\n--- Final Report ---")
for key, value in student.items():
print(f"{key.capitalize()}: {value}")Run & Test:
=== Student Grade Book ===
Student name: Priya
Maths: 95
Science: 88
English: 92
--- Final Report ---
Name: Priya
Marks: [95.0, 88.0, 92.0]
Total: 275.0
Average: 91.67
Grade: A+Common Mistakes & Fixes
| Mistake | Error | Fix |
|---|---|---|
| student["phone"] (key not found) | KeyError | Use .get("phone", "N/A") |
| student["marks"] = 90 (should be list) | Wrong data | Use student["marks"] = [90, 85] |
| Duplicate keys | Last one overwrites | Avoid same key names |
Day 7 Wrap-Up
You learned:
- Create & access dictionaries (dict["key"])
- Use .keys(), .values(), .items(), .update()
- Built a Student Grade Book with grade logic
- Looped through .items() with for loop
Track Progress (in your notebook):
Day 7 Done: Dictionaries are OP! Built a grade book. Doubt: .get() vs []? Answer: .get() is safe – no error if key missing, can give default value.
Resources:
- RealPython: Dictionaries
- W3Schools: Dictionaries
- YouTube: “Python Dictionaries freeCodeCamp” (first 15 mins)



Use full contents
ReplyDelete