← Intro to programming with Python

Dictionaries: look up by key

Store pairs like word → meaning or item → price.

Start this lesson

A dictionary stores pairs: each KEY is linked to a VALUE, like a word and its meaning, or a menu item and its price. You write it with curly braces: prices = {"tea": 2.5, "cake": 4}. To look something up, use the key in square brackets: prices["tea"] gives 2.5. Why not a list? With a list you need to remember positions; with a dictionary you just ask for the thing by name.

prices = {"tea": 2.5, "cake": 4.0, "juice": 3.0}
print(prices["cake"])          # 4.0
prices["muffin"] = 3.5         # add a new pair
prices["tea"] = 2.75           # update a value
print(prices.get("soup", 0))   # 0  (not on the menu)
print("juice" in prices)       # True

Assigning to a key adds it if it is new, or replaces its value if it already exists. get() gives a default instead of an error when a key is missing.

Common mistake: asking for a key that does not exist, like prices["soup"]. That gives a KeyError. Check first with in, or use prices.get("soup", 0).

Keys must be unique. Writing the same key twice keeps only the last value.

in checks the KEYS, not the values: "tea" in prices is True, but 2.75 in prices is False.