As dictionaries grow, we need more than CRUD—we need to inspect, access safely, merge in bulk, and compute summaries. Python offers keys(), values(), and items() as three “windows” for viewing keys, values, and key–value pairs. Use get() for safe access with defaults, update() for batch merging, pop() to remove and capture a value, and setdefault() to guarantee a default structure when grouping or counting. For iteration, the typical pattern is unpacking over items(): for k, v in d.items(), which is both clear and efficient.
keys(), values(), and items() are dynamic views, they reflect live changes in the dictionary.
Example A:
student = {"name": "Alice", "age": 12, "grade": 6}
print(student.keys()) # dict_keys(['name','age','grade'])
print(student.values()) # dict_values(['Alice',12,6])
print(student.items()) # dict_items([('name','Alice'),('age',12),('grade',6)])
get(key, default) avoids KeyError by returning a fallback.
Example B:
print(student.get("school", "N/A")) # N/A
update() merges right-hand entries into the left-hand dictionary.
Example C:
student.update({"school": "STEM", "age": 13})
print(student) # {'name':'Alice','age':13,'grade':6,'school':'STEM'}
pop(key, default) removes and returns a value; returns default if missing.
Example D:
removed = student.pop("grade", None)
print("removed:", removed)
setdefault(key, default) inserts a default when missing, handy for grouping.
Example E:
groups = {}
for name in ["Ann","Amy","Bob","Ben"]:
first = name[0]
groups.setdefault(first, []).append(name)
print(groups) # {'A':['Ann','Amy'], 'B':['Bob','Ben']}
2. Iteration Patterns
Example F: Unpacking over items
scores = {"Tom":88, "Amy":95, "Leo":78}
for name, score in scores.items():
print(f"{name}: {score}")
Example G: Keys & Values only
for name in scores.keys():
pass # use name
for score in scores.values():
pass # use score
Example H: Filtering & Summaries
# count how many scores >= 90
count_a = sum(1 for s in scores.values() if s >= 90)
# build a passed-only dict
passed = {n: s for n, s in scores.items() if s >= 60}
Example I: Nested Dicts
roster = {
"S001": {"name":"Alice", "scores":{"math":95, "eng":88}},
"S002": {"name":"Bob", "scores":{"math":82, "eng":91}},
}
for sid, info in roster.items():
total = sum(info["scores"].values())
print(sid, info["name"], "total:", total)
Square-bracket access on missing keys raises KeyError; use get() when unsure. Remember to unpack pairs from items(). update() overwrites same-name keys—decide precedence first. setdefault() returns a reference; mutating it changes the dict content.
Hands-on Practice:
{"Tom":{"math":90,"eng":85}, "Amy":{"math":95,"eng":91}, ...}, iterate to print each student’s total and average, then show the top N by average in descending order (N from user input, default to 3 on invalid input). Handle missing subjects or empty score dicts safely (treat as 0).Output example:
Tom | total=175 | avg=87.50
Amy | total=186 | avg=93.00
Leo | total= 78 | avg=78.00
Eve | total= 0 | avg= 0.00
Top N (default 3): 2
=== Top by average ===
Amy | total=186 | avg=93.00
Tom | total=175 | avg=87.50
Answer example:
def student_total_avg(scores_dict):
if not scores_dict:
return 0, 0.0
vals = list(scores_dict.values())
total = sum(v for v in vals if isinstance(v, (int, float)))
count = sum(1 for v in vals if isinstance(v, (int, float)))
avg = (total / count) if count else 0.0
return total, avg
def report_all(class_dict):
report = []
for name, subj_scores in class_dict.items():
total, avg = student_total_avg(subj_scores.get("scores", subj_scores))
report.append((name, total, avg))
return report
def top_n_by_avg(report, n=3):
n = n if isinstance(n, int) and n > 0 else 3
return sorted(report, key=lambda x: x[2], reverse=True)[:n]
cls = {
"Tom": {"scores": {"math": 90, "eng": 85}},
"Amy": {"scores": {"math": 95, "eng": 91}},
"Leo": {"scores": {"math": 78}},
"Eve": {"scores": {}},
}
rep = report_all(cls)
for name, total, avg in rep:
print(f"{name:>3} | total={total:3} | avg={avg:5.2f}")
raw = input("Top N (default 3): ").strip()
try:
N = int(raw) if raw else 3
except:
N = 3
top = top_n_by_avg(rep, N)
print("n=== Top by average ===")
for name, total, avg in top:
print(f"{name:>3} | total={total:3} | avg={avg:5.2f}")
Highlights unpacking with items() on nested dicts, safe access with get(), input defaults, and sorting with sorted(..., key=..., reverse=True). With these methods and iteration patterns, you can generate structured reports. Thus, we can combine functions + dictionaries + lists into a more complete mini-system, such as student records, inventory, or word-frequency analyzers.