🟢 Day 5 — Dictionaries (Key–Value Thinking)
1️⃣ Why Lists Are Not Enough
So far, we used lists:
names = ["Amit", "Rahul", "Neha"]
marks = [85, 90, 78]
Problem ❌
Which mark belongs to which student? You must remember positions Data can easily get mismatched 💡 Lists work well when order matters,
but fail when meaning matters.
2️⃣ Real-World Analogy
Think of a phone contacts app:
You don’t say: “Give me contact at position 5” You say: “Give me Rahul’s number” That is key → value.
🧠 Dictionary = lookup by meaning, not position
3️⃣ What Is a Dictionary?
A dictionary stores data as:
Example:
marks = {
"Amit": 85,
"Rahul": 90,
"Neha": 78
}
Order is not important (for beginners) 4️⃣ Accessing Values
🧠 You don’t “search”.
You directly look up using key.
5️⃣ What If Key Does Not Exist? (Very Important)
❌ Program crashes.
Why?
Dictionary does not guess Safer Way
if "Suresh" in marks:
print(marks["Suresh"])
else:
print("Student not found")
🧠 Always check before accessing.
6️⃣ Adding & Updating Values
Add New Key
Update Existing Key
Same syntax.
Python decides whether it’s add or update.
7️⃣ Looping Over Dictionary
Loop Over Keys
for name in marks:
print(name)
Loop Over Values
for score in marks.values():
print(score)
Loop Over Both
for name, score in marks.items():
print(name, score)
🧠 .items() is the most used pattern.
8️⃣ Frequency Counting Pattern (EXTREMELY IMPORTANT)
This pattern appears everywhere:
Example: Count Characters
text = "programming"
freq = {}
for ch in text:
if ch in freq:
freq[ch] += 1
else:
freq[ch] = 1
print(freq)
How to Think
🧠 This is one of the most important thinking patterns in programming.
9️⃣ Dictionary vs List (Mental Model)
⚠️ Common Beginner Mistakes
Forgetting to check key existence Confusing keys and values Using mutable types as keys Overusing lists where dict is better 🧪 Practice Questions (Think Before Coding)
Q1
Create a dictionary to store student → marks and print all students with their marks.
Q2
Given a dictionary of items and prices, calculate total cost.
Q3
Count frequency of numbers in a list.
Example:
[1, 2, 1, 3, 2, 1]
→ {1: 3, 2: 2, 3: 1}
Q4
Count frequency of words in a sentence.
Example:
"the cat and the dog and the cat"
Q5
Find the student with highest marks.
Q6
Merge two dictionaries.
If key exists in both, add values.
Q7 (Thinking Question)
Why is dictionary better than list for storing marks?
Answer in words.
🔑 HINTS (Read Together, Only If Stuck)
Start frequency count from 1 Use .items() to loop key + value Think in mapping, not position ✅ What You Should Be Able to Do Now
After Day 5, you should:
Store meaningful data using keys Process real-world structured data Choose dictionary over list correctly 🧠 Reflection Questions (Answer in Words)
Why do keys need to be unique? What happens if key does not exist? When should you prefer dictionary over list? Why is frequency counting so common? ⭐ Golden Rule from Day 5
If data has meaning,
it deserves a dictionary.