Dictionaries in Python: look things up by key
How many sage mediums are in stock? In a list you'd have to remember which position that is. In a dictionary you just ask by name.
The big idea
A dictionary maps unique keys to values, so you can store and retrieve data by a meaningful name instead of a position.
See it in code
Curly braces hold key: value pairs. Square brackets look a value up, or assign a new one:
stock = {"TEE-SAGE-M": 12, "TEE-OAT-L": 3, "PANTS-OAT-L": 15}
print("TEE-OAT-L in stock:", stock["TEE-OAT-L"])
stock["TEE-SAGE-M"] = stock["TEE-SAGE-M"] - 2
print("TEE-SAGE-M after the sale:", stock["TEE-SAGE-M"])TEE-OAT-L in stock: 3 TEE-SAGE-M after the sale: 10
Assigning to an existing key updates its value. Assigning to a key that doesn't exist yet adds it; that's how a new product enters the catalog.
Looking up a missing key with brackets raises KeyError. get() returns a default you choose instead, and .items() lets a loop see each key with its value:
stock = {"TEE-SAGE-M": 10, "TEE-OAT-L": 3, "PANTS-OAT-L": 15}
print("TEE-SAGE-XL in stock:", stock.get("TEE-SAGE-XL", 0))
for sku, count in stock.items():
print(f"{sku}: {count}")TEE-SAGE-XL in stock: 0 TEE-SAGE-M: 10 TEE-OAT-L: 3 PANTS-OAT-L: 15
stock.get("TEE-SAGE-XL", 0) answered 0 without crashing. for sku, count in stock.items() unpacks each pair into two loop variables.
get(key, 0) + n is the classic counting pattern. It starts every new key at zero and adds to keys it has already seen:
orders = ["TEE-SAGE-M,2,38.00", "PANTS-OAT-L,1,78.00", "TEE-CLAY-S,3,38.00", "TEE-SAGE-M,1,38.00"]
sold = {}
for order in orders:
fields = order.split(",")
sku = fields[0]
quantity = int(fields[1])
sold[sku] = sold.get(sku, 0) + quantity
print("Units sold:", sold)Units sold: {'TEE-SAGE-M': 3, 'PANTS-OAT-L': 1, 'TEE-CLAY-S': 3}TEE-SAGE-M appears twice in the batch, and its two quantities were combined into one total of 3. The dictionary built its own keys as it went.
Lookup tables are everywhere. A codon maps to an amino acid, a ticker to its latest price, a username to a profile, a word to how often it appears.
Try it yourself
Add a restock alert: loop over stock and print every SKU below a reorder_point of 12. Then look up stock["tee-sage-m"] in lowercase and read the error you get.
The common mistake
Assuming keys are forgiving. "tee-sage-m" and "TEE-SAGE-M" are different keys, and the wrong one raises KeyError. Normalize case before you look up, or use get() when a key might be absent.
What it unlocks
Dictionaries pair naturally with string methods for parsing and accumulators for counting. When each record needs behavior as well as data, move up to classes.