Beginner · 10 min
Named data with dictionaries
Store related values under meaningful keys.
Look up a key
A dictionary stores key-value pairs inside braces. Put a colon between each key and value. Use a key in square brackets to retrieve its value.
product = {"name": "Notebook", "price": 4}
print(product["name"])
print(product["price"])Output
Notebook 4
Update or add a value
Assign to a key to update it or add a new one. get() can supply a default when a key is missing; direct indexing of a missing key raises an error.
product = {"price": 4}
product["price"] = 5
print(product["price"])
print(product.get("stock", 0))Output
5 0
Named data with dictionaries
- Pair each key with its value.
- Compare an existing key with a missing key.
Try it yourself
Code runs on this device. When you are signed in, drafts sync to your account.
Update a product
Change the product price to 6. Store price multiplied by quantity in total, then display total.
Update product["price"], then multiply the two dictionary values.