Lesson explanation
After this lesson, you will be able to:
.get(key, default) to read optional keys while preserving existing falsy values..items() and unpack each pair.Dictionaries map names to values. The previous lesson covered record[key], which raises KeyError for a missing key. When an optional field is expected, record.get(key, fallback) returns the fallback only if the key is missing. A present value of 0, False, "", or None remains unchanged.
A dictionary is iterable: for key in record visits its keys. The explicit methods .keys() and .values() let you access just keys or values. Use .items() when you need both: each iteration supplies a (key, value) pair that you can unpack.
Modern Python dictionaries preserve insertion order, so looping over an unchanged dictionary follows the order its entries were inserted. This does not mean keys are numeric indexes, and it does not imply alphabetical sorting.
A dictionary's .get() is for lookup; .items() is for pair iteration. They solve different problems and become especially powerful when combined with conditional counts.
The fallback applies only when the key is absent.
limits = {"retries": 0, "timeout": 15}
print(limits.get("retries", 3))
print(limits.get("workers", 2))Output:
0
2Iterating over the dictionary directly gives its keys; .keys() makes that intention explicit.
channels = {"email": True, "sms": False}
for channel in channels.keys():
print(f"Channel: {channel}")Output:
Channel: email
Channel: smsUse .values() when the keys do not affect the calculation.
durations = {"lint": 8, "build": 12, "test": 20}
total = 0
for duration in durations.values():
total += duration
print(f"Total: {total}")Output:
Total: 40.items() supplies each label and its corresponding value together.
statuses = {"api": "ready", "worker": "paused"}
for name, status in statuses.items():
print(f"{name}: {status}")Output:
api: ready
worker: paused| Need | Python |
|---|---|
| Optional lookup | record.get("name", "unknown") |
| Keys only | record.keys() or for key in record |
| Values only | record.values() |
| Keys and values | record.items() |
| Loop through pairs | for key, value in record.items(): |
record.get("key", default) does not replace a present falsy value.for a, b in record iterates keys, not pairs; use .items() to unpack entries..keys(), .values(), and .items() return views, not ordinary list copies..values() loses the associated key label when your output needs both.