Skip to content

Day 5 — Dictionaries - Hashmap

🟢 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:
key → value
Example:
marks = {
"Amit": 85,
"Rahul": 90,
"Neha": 78
}
Keys are unique
Values can repeat
Order is not important (for beginners)

4️⃣ Accessing Values

print(marks["Amit"])
🧠 You don’t “search”. You directly look up using key.

5️⃣ What If Key Does Not Exist? (Very Important)

print(marks["Suresh"])
❌ Program crashes.
Why?
Dictionary does not guess
Key must exist

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

marks["Suresh"] = 88

Update Existing Key

marks["Amit"] = 90
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:
Word count
Character count
Votes
Logs
Analytics

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

Check if key exists
If yes → increment
If no → initialize
🧠 This is one of the most important thinking patterns in programming.

9️⃣ Dictionary vs List (Mental Model)

List
Dictionary
Access by index
Access by key
Order-based
Meaning-based
Position matters
Name matters
Slower search
Fast lookup
There are no rows in this table

⚠️ Common Beginner Mistakes

Forgetting to check key existence
Confusing keys and values
Using mutable types as keys
 
Want to print your doc?
This is not the way.
Try clicking the ··· in the right corner or using a keyboard shortcut (
CtrlP
) instead.