🟢 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