Beginner � 22 min
Dictionaries: key-value data
Prerequisite: Tuples & Sets lesson complete karo pehle.
WHY: real-world data represent karna
Dictionaries real-world data ko represent karti hain � student records, API responses, configuration settings. Har value ka ek unique key hota hai, jaise dictionary mein word ka meaning.
python
student = {
"name": "Aman",
"age": 22,
"course": "Data Science"
}
print(student["name"]) # Aman
print(student.get("city", "Lucknow")) # Lucknow (default)KEY-VALUE
Har item ka key aur value hota hai.
MUTABLE
Values update, add aur remove kar sakte ho.
FAST
Key se direct lookup hota hai (O(1)).
WHEN: kab use hota hai
APIs se data aata hai toh dictionary hota hai. Config files, JSON data, database records � sab dictionaries hain.
HOW: dictionary operations
python
# Add/update
student["email"] = "aman@email.com"
student["age"] = 23
# Loop through dictionary
for key, value in student.items():
print(f"{key}: {value}")
# Nested dictionary
students = {
"aman": {"age": 22, "marks": 85},
"priya": {"age": 21, "marks": 92}
}
print(students["priya"]["marks"]) # 92Try it: student record systemDictionary update karke run karo
Run Python dabayein
Useful dictionary operations
student.keys()saari keys deta hai.student.values()saari values deta hai.student.items()key-value tuples deta hai."name" in studentkey exist karti hai ya nahi check karta hai.student.pop("age")key remove karke value return karta hai.
Quick check
Ek dictionary banao jisme student ka name aur age ho. Answer mein dictionary format use karo.
Curly braces mein key-value pairs likho, keys ko quotes mein rakho.
Common mistakes
- Key string hoti hai:
student["name"]Sahi hai,student[name]se error aata hai. - Empty dictionary
dict()ya{}se banta hai. - Key duplicate nahi ho sakti; agar same key do baar likho toh last value override hoti hai.
Key-value data handle karna aa gaya?
Ab operators seekho � arithmetic, comparison aur logical operations Python mein kaise hote hain.