Collections
Dictionaries
Use a dictionary as a small record when fields have names. Direct indexing communicates that the key is required, while get() communicates that a missing key has a fallback.
Source
profile = {"name": "Ada", "language": "Python"}
profile["year"] = 1843
print(profile["name"])
print(profile.get("timezone", "UTC"))Output
Ada
UTCUse a dictionary as a lookup table when keys identify values. This is different from a list, where numeric position is the lookup key.
Source
scores = {"Ada": 10, "Grace": 9}
print(scores["Grace"])
print(scores.get("Guido", 0))Output
9
0Use items() when the loop needs both keys and values. It avoids looping over keys and then indexing back into the dictionary.
Source
for name, score in scores.items():
print(f"{name}: {score}")Output
Ada: 10
Grace: 9Mutating a dictionary while iterating it raises RuntimeError. Snapshot the keys with list(d.keys()) (or build a list of changes and apply them after the loop) so the iteration sees a stable view.
Source
inventory = {"apple": 0, "pear": 3, "plum": 0}
for name in list(inventory.keys()):
if inventory[name] == 0:
del inventory[name]
print(inventory)Output
{'pear': 3}Notes
- Dictionaries preserve insertion order in modern Python.
- Use
get()when a missing key has a reasonable default. - Use direct indexing when a missing key should be treated as an error.
- Snapshot keys with
list(d.keys())before deleting items in a loop; mutating during iteration raisesRuntimeError.
See also
Run the complete example
Expected output
Ada
UTC
9
0
Ada: 10
Grace: 9
{'pear': 3}
Execution time appears here after you run the example.