Dicts

A dict maps keys to values: volumes = {"A01": 50.0, "A02": 40.0}. Looking up a key is O(1) on average, no matter how big the dict is.

  • volumes["A01"] raises KeyError if the key is missing.
  • volumes["A03"] = 35.0 adds a key, or replaces the value if it exists.
  • "A01" in volumes checks the keys, not the values.
  • for key, value in volumes.items(): loops over both.

Dicts remember insertion order, so they loop in the order keys were added. Keys must be hashable, which in practice means immutable: strings, numbers and tuples work, lists don't. A later page explains why.

Counting things is the classic dict job: start each new key at 0, then add 1.

Exercise: finish count_by_plate so it counts how many records each plate has. Press Check to run the tests.