Looping and Updating Mappings
Scenario: A report must print both every service name and its port.
New words, in plain English
- items view - the key-value pairs returned by
.items() - Membership -
key in mappingchecks keys - Merge - combining mappings
Loop over .keys(), .values(), or .items(). update merges values; setdefault supplies a value only when the key is absent. Modern Python also supports a | b for a new merged dict.
Analogy: A Python program is like a clear set of instructions for a careful helper: names label things, indentation groups steps, and errors explain where the helper became confused.
A small, real example
ports = {"api": 80, "db": 5432}
for name, port in ports.items():
print(f"{name}:{port}")
Tip: Do not add or remove dictionary keys while directly iterating over it; iterate over list(mapping) if mutation is necessary.
Goal: Practice this idea in the py-dict-basics challenge at/labs/python. Fix the broken program, run it yourself, then usecheckto prove the real end state.