Python Tutorial / Store Key–Value Data with Dictionaries

A dictionary looks up values by key. Use it for named record fields or category totals, and decide explicitly whether an absent key is an error or should use a default.

Understand keys and replacement

Dictionary literals contain key: value pairs inside braces. Assigning an existing key replaces its value rather than adding another occurrence. Keys must be hashable; strings and integers are common choices, whereas lists are unsuitable. String keys distinguish letter case and surrounding spaces.

expense = {"name": "lunch", "amount": 8000}
expense["amount"] = 9000
print(expense["amount"])

The updated amount is 9000. Dictionary iteration preserves insertion order, but does not automatically sort by name or value. Request an explicit sorted order when the output requires one.

For the relevant APIs and platform requirements, see Store Key–Value Data with Dictionaries documentation.

Build category totals

Save the complete code below as dicts.py in a separate practice folder, using UTF-8. Run python dicts.py in a terminal with your project virtual environment selected. Outside a virtual environment on macOS or Ubuntu, use python3 when that is your interpreter command.

expenses = [("food", 8000), ("transport", 2500), ("food", 3500)]
totals = {}
for category, amount in expenses:
    totals[category] = totals.get(category, 0) + amount
for category, total in sorted(totals.items()):
    print(category, total)
print(totals.get("books", 0))

Expected output:

food 11500
transport 2500
0

Choose required lookup or a default

totals["books"] raises KeyError if the key is absent. totals.get("books", 0) returns zero without inserting that key. A default is appropriate for the first contribution to a total, but can conceal an invalid record if a required field is missing.

Iterate the dictionary itself for keys, values() for values, or items() for pairs. Dictionary copies are shallow by default, so lists stored as values can remain shared with the original.

Test normalization and collection changes

  1. Change the food amount 3500 to 4500 and check that only the food total becomes 12500.
  2. Replace one food key with Food and observe the separate group. Choose a normalization policy deliberately.
  3. If books is a required category, test for its existence instead of silently treating absence as zero.

Adding or deleting keys while iterating the same dictionary can raise RuntimeError. Collect the intended keys first or build a new dictionary. Do not let a convenient default decide whether missing business data is valid.