Lesson 14 of 19 · 4 min
Dictionaries — Key-Value Pairs
WHY Dictionaries?
[85, 92, 78] — whose score is whose? You cannot tell. {"Priya": 85, "Ahmed": 92, "Ravi": 78} — now each score has a label. Dictionaries map keys (labels) to values (data), just like a real dictionary maps words to their definitions.
Creating and Accessing
student = {
"name": "Priya Sharma", # string key → string value
"age": 20, # string key → integer value
"branch": "CSE",
"cgpa": 3.75,
"is_hosteler": True # any type can be a value
}
# Access by key — square bracket notation
print(student["name"]) # Priya Sharma
print(student["cgpa"]) # 3.75
# SAFE access — .get() returns None (not an error!) if key is missing
print(student.get("phone")) # None — key doesn't exist, no crash
print(student.get("phone", "N/A")) # N/A — custom default value
Output: Priya Sharma 3.75 None N/A
Adding, Updating, and Removing
student = {"name": "Priya", "age": 20}
student["branch"] = "CSE" # ADD a new key-value pair
student["age"] = 21 # UPDATE existing key — old value replaced
print(student) # {'name': 'Priya', 'age': 21, 'branch': 'CSE'}
del student["age"] # DELETE a key (raises KeyError if key absent)
print(student) # {'name': 'Priya', 'branch': 'CSE'}
val = student.pop("branch") # remove key AND return its value
print(f"Removed: {val}") # Removed: CSE
print(student) # {'name': 'Priya'}
Output:
{'name': 'Priya', 'age': 21, 'branch': 'CSE'}
{'name': 'Priya', 'branch': 'CSE'}
Removed: CSE
{'name': 'Priya'}Important Dictionary Methods
scores = {"Priya": 85, "Ahmed": 92, "Ravi": 78}
print(list(scores.keys())) # ['Priya', 'Ahmed', 'Ravi'] — all keys
print(list(scores.values())) # [85, 92, 78] — all values
print(list(scores.items())) # [('Priya', 85), ('Ahmed', 92), ('Ravi', 78)]
# .update() — merge another dict in; existing keys get overwritten
scores.update({"Sara": 88, "Ahmed": 95}) # adds Sara, overwrites Ahmed's old score
print(scores) # {'Priya': 85, 'Ahmed': 95, 'Ravi': 78, 'Sara': 88}
# .setdefault() — insert key with default ONLY if key does NOT already exist
scores.setdefault("Meera", 0) # Meera not in dict → adds Meera: 0
scores.setdefault("Priya", 0) # Priya already exists → does NOT overwrite her 85
print(scores) # Priya still 85; Meera is 0
Output:
['Priya', 'Ahmed', 'Ravi']
[85, 92, 78]
[('Priya', 85), ('Ahmed', 92), ('Ravi', 78)]
{'Priya': 85, 'Ahmed': 95, 'Ravi': 78, 'Sara': 88}
{'Priya': 85, 'Ahmed': 95, 'Ravi': 78, 'Sara': 88, 'Meera': 0}Iterating Through a Dictionary
scores = {"Priya": 85, "Ahmed": 92, "Ravi": 78, "Sara": 65}
# Loop through keys (default behaviour when you loop over a dict)
for name in scores:
print(name) # prints: Priya, Ahmed, Ravi, Sara
# Loop through values only
for score in scores.values():
print(score) # prints: 85, 92, 78, 65
# Loop through BOTH key and value — by far the most common pattern
for name, score in scores.items():
grade = "Pass" if score >= 60 else "Fail" # ternary expression
print(f"{name}: {score} → {grade}")
Output: Priya Ahmed Ravi Sara 85 92 78 65 Priya: 85 → Pass Ahmed: 92 → Pass Ravi: 78 → Pass Sara: 65 → Pass
Dictionary Comprehension
# Pattern: {key_expr: value_expr for item in iterable if condition}
squares = {i: i**2 for i in range(1, 6)} # {1:1, 2:4, 3:9, 4:16, 5:25}
even_sq = {i: i**2 for i in range(1, 11) if i % 2 == 0} # only even numbers
print(squares)
print(even_sq)
# Build from two parallel lists using zip()
keys = ["name", "age", "city"]
vals = ["Priya", 20, "Chennai"]
profile = {k: v for k, v in zip(keys, vals)} # zip() pairs them up
print(profile)
Output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
{2: 4, 4: 16, 6: 36, 8: 64, 10: 100}
{'name': 'Priya', 'age': 20, 'city': 'Chennai'}Nested Dictionaries — Data Inside Data
students = {
"S001": {"name": "Priya", "cgpa": 3.75, "branch": "CSE"},
"S002": {"name": "Ahmed", "cgpa": 3.50, "branch": "ECE"},
"S003": {"name": "Ravi", "cgpa": 3.90, "branch": "CSE"},
}
# Access: outer key → inner key chained
print(students["S001"]["name"]) # Priya
print(students["S003"]["cgpa"]) # 3.9
# Loop through all records
for sid, info in students.items():
status = "Distinction" if info["cgpa"] >= 3.7 else "Pass"
print(f"{sid} | {info['name']} | CGPA {info['cgpa']} | {status}")
Output: Priya 3.9 S001 | Priya | CGPA 3.75 | Distinction S002 | Ahmed | CGPA 3.5 | Pass S003 | Ravi | CGPA 3.9 | Distinction
