π Quick Info
- Topic: Dictionaries in Python
- Target Audience: Beginners who know lists and loops
- Goal: Understand how to store and look up data by key
1. Introduction
"Lists let me store many items. But what if I want to find something by name instead of position? That's when I learned about dictionaries β and now they're my favorite data structure."
2. The Problem (Without Dictionaries)
names = ["Ali", "Sara", "Ahmed"]
ages = [25, 30, 28]
# To find Ali's age, I have to:
index = names.index("Ali")
print(ages[index])
Problem: Two Lists, manual lookup, easy to mess up.
3. The Solution (With Dictionaries)
people = {
"Ali": 25,
"Sara": 30,
"Ahmed": 28
}
print(people["Ali"])
Output:
25
4. How It Works (Line By Line)
Line 1-5: A dictionary with curly braces. Each entry has a key(name) and a value(age).
Line 7: people[ββAliββ] looks up the value for the key βAliβ.
5.Common Dictionary Operations
person = {"name": "Ali", "age": 25}
person["city"] = "Karachi"
print(person.get("country", "Unknown")) # Unknown
for key, value in person.items():
print(f"{key}: {value}")
Output:
name:Ali
age: 25
city:Karachi
6. Real Examples (My Practice)
scores = {"Ali": 85, "Sara": 92, "Ahmed": 78}
top_student = max(scores, key=scores.get)
print(f"Top student: {top_student} with {scores[top_student]}")
Output:
Top student: Sara with 92
7. What I learned
- Dictionaries store key-value pairs.
- keys must be unique.
- [ ] accesses a value- throws error if key doesn't exist.
- .get() returns a default instead of throwing an erroring.
- .items() loops through both keys and values.
8.Conclusion
βDictionaries felt weird at first with all the curly braces. But once I used them to store real data, I never went back. They're the fastest way to lookup information by name.β
Top comments (0)