Collections

Dictionaries

Dictionaries map keys to values for records, lookup, and structured data.

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
UTC
HASH → BUCKET0"a" → 11"b" → 22"c" → 3"d" → 4collision
Each key is hashed to a bucket; collisions chain into the next slot. Lookup is constant-time on average.

Use 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
0

Use 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: 9

Mutating 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

See also

Run the complete example

Example code

Expected output

Ada
UTC
9
0
Ada: 10
Grace: 9
{'pear': 3}

Execution time appears here after you run the example.