script_15.py - Dictionary Iteration
Code
#!/usr/bin/env python3
"""Dictionary iteration"""
student_scores = {
"Alice": 95,
"Bob": 87,
"Charlie": 92,
"Diana": 88
}
for name, score in student_scores.items():
print(f"{name}: {score}")
Explanation
Line 4-9: Dictionary definition
- {} syntax creates a dictionary (dict type)
- Dictionary stores key-value pairs
- Keys: "Alice", "Bob", etc. (strings)
- Values: 95, 87, etc. (integers)
- : separates key from value
- , separates pairs
- student_scores is dict type
Line 11: for name, score in student_scores.items():
- .items() is a dict method that returns key-value pairs
- Returns an iterable of tuples: ("Alice", 95), ("Bob", 87), etc.
- Tuple unpacking: name, score gets both values from each tuple
- name gets the key (string)
- score gets the value (integer)
- Iterates through all dictionary entries
- Order is insertion order (Python 3.7+)
Line 12: print(f"{name}: {score}")
- Both variables available from tuple unpacking
- Prints each key-value pair