A store stores a product name, price and stock amount.
What You Need to Understand
A dictionary represents one record as named fields. Compared with positional list indexes, key names make the meaning of each value explicit.
When to Use It
A store stores a product name, price and stock amount.
Step-by-Step Python Example
product = {"name": "Keyboard", "price": 49.9, "stock": 12}
print(product["name"])
product["stock"] -= 1
print(product)
How the Example Works
The dictionary uses keys for lookup and assignment. Updating stock changes the entry associated with stock.
Example Output
Keyboard
{'name': 'Keyboard', 'price': 49.9, 'stock': 11}
Maya is 28
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
person = {"name": "Maya", "age": 28}
print(f"{person['name']} is {person['age']}")
Important Behavior and Edge Cases
Do not blindly assume a key exists in imported data. Use get() or explicit validation when fields are optional.
Try It Yourself
Add a category field and print a short inventory summary.
Common Beginner Mistakes
- Do not blindly assume a key exists in imported data. Use
get()or explicit validation when fields are optional. - Treating missing dictionary keys, replacement precedence, and shallow copies as if they had identical behavior in every context.
Key Takeaways
- A dictionary represents one record as named fields.
- The dictionary uses keys for lookup and assignment.
- Do not blindly assume a key exists in imported data.