Python reference
Dictionaries
Also called: dict · key-value · lookup table · hash map · .get()
Definition
A dictionary maps keys to values, as in {"red": 2, "green": 5}, and looks values up by key in roughly constant time.
Picture it
Use a dict whenever you would otherwise search a list for a name: configuration settings, a part number to its price, a colour to its digit. d.get(key, default) avoids a KeyError when a key may be missing.
Worked example
prices = {"motor": 4.5, "wheel": 1.2}. A robot needs 2 motors and 4 wheels. What does 2 * prices["motor"] + 4 * prices["wheel"] give? What does prices.get("sensor", 0) give?
- 2 × 4.5 = 9.0
- 4 × 1.2 = 4.8
- 9.0 + 4.8 = 13.8
- Missing key with a default → 0
Answer13.8 and 0.
✓ The 2 numbers in this answer are recomputed from scratch by an automated test.
In Python
colour_digit = {"black": 0, "brown": 1, "red": 2}
for name, d in colour_digit.items():
print(name, d)Common misconceptions
- Misconception: Keys must be hashable: a list cannot be a key, but a tuple can.
- Misconception: Since Python 3.7 dicts keep insertion order, but they are still not meant for positional indexing.