0
Dictionary Lookups1 / 4

CRASH COURSE

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))