Learning LibraryCore Coding LibraryTeens

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

1The basics

Curly braces hold key: value pairs. Square brackets look a value up, or assign a new one:

python
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"])
Run it. Look up, then record a sale:
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.

2A step further

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:

python
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}")
Run it. A size we don't make, then the whole report:
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.

3At Evergreen

get(key, 0) + n is the classic counting pattern. It starts every new key at zero and adds to keys it has already seen:

python
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)
Run it. Units sold per SKU from a batch of orders:
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.

The same idea, everywhere

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.

Want the simpler version? Read the Kids version →