← All lessons

Lesson 11

Dictionary Lookups

A dictionary associates a unique key with a value. Unlike list indexes, keys can be meaningful names such as "price".

Square brackets retrieve a required key and raise KeyError when it is missing. get(key, default) is useful when absence is expected.

Assign to a key to update its value. Adding an unused key creates a new entry; assigning an existing key replaces its old value.

product = {"name": "Notebook", "price": 4}
product["price"] = 5
print(product.get("stock", 0))

Check your understanding

What does {"a": 1}.get("b", 0) return?

CHALLENGE

Create product with price 4. Update price to 5, then print the price and missing stock with a default of 0 on separate lines.

Practice →
Next: Sets & Uniqueness →