Collections
Dictionaries
Dictionaries are Python's built-in mapping type. They exist for data where names or keys are more meaningful than numeric positions: records, lookup tables, counters, and JSON-like payloads.
Use direct indexing when a key is required. Use get() when absence is expected and the code has a reasonable fallback.
Unlike lists, dictionaries answer “what value belongs to this key?” rather than “what value is at this position?” Iterating with items() keeps each key next to its value.
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: 9Adding or removing keys while iterating a dictionary raises RuntimeError ("dictionary changed size during iteration"); reassigning an existing key's value is allowed. Snapshot the keys with list(d.keys()) (or build a list of changes and apply them after the loop) so deletions see 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; adding or removing keys 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.