Python · Beginner level

Beginner level · Module 3: Working with Lists, Dictionaries and Strings · Lesson 2 of 3

Dictionaries for Real Records

Use key–value pairs to represent records such as a product with a name, price and stock level.

In this lesson you will

  • Create, read and update dictionary entries
  • Loop over keys and values with items()

Key concepts

key/valueget() with defaultitems()list of dictionaries

The lesson

A dictionary stores pairs of keys and values, like a price list: prices = {"rice": 3500, "sugar": 2800}. You look up a value by its key — prices["rice"] — rather than by position.

Looking up a key that does not exist raises a KeyError. Use prices.get(item) when a missing key is possible; it returns None (or a default you choose) instead of crashing. Loop over pairs with for item, price in prices.items().

Real records are often a list of dictionaries: each learner, product or sale is one dictionary with the same keys. This is the same shape as rows in a spreadsheet, and it is how data from files and APIs usually arrives.

Step by step

  1. Create a dictionary of five products and their prices in SSP.
  2. Ask the user for a product name and clean it with strip().lower().
  3. Look it up with get() and print the price or a friendly 'not found' message.
  4. Loop over items() to print the full price list.
Code example

Market stall daily summary

Use a list of dictionaries and a loop to total a day's sales by product — the shape most real data arrives in.

Pythondaily_summary.py
sales = [    {"item": "rice", "qty": 3, "price": 3500},    {"item": "sugar", "qty": 2, "price": 2800},    {"item": "rice", "qty": 1, "price": 3500},    {"item": "soap", "qty": 4, "price": 1200},] totals = {}  # item -> revenue in SSPfor sale in sales:    revenue = sale["qty"] * sale["price"]    totals[sale["item"]] = totals.get(sale["item"], 0) + revenue for item, revenue in sorted(totals.items(), key=lambda pair: pair[1], reverse=True):    print(f"{item:<6} {revenue:>7,} SSP") print(f"Total  {sum(totals.values()):>7,} SSP")

Output

rice    14,000 SSP
sugar    5,600 SSP
soap     4,800 SSP
Total   24,400 SSP

How it works

Each sale is a dictionary, like one row in a spreadsheet. The loop calculates the revenue for each sale and adds it to a running total for that item; totals.get(item, 0) starts a new item at zero. sorted(..., reverse=True) lists the best-selling item first, and the format codes <6 and >7, line the columns up and add thousands separators.

Key concepts

list of dictionariesaccumulator patterndict.get with a defaultsorted with keyf-string alignment

Where you would use it

The same pattern totals fees by class, stock by warehouse or survey answers by district.

Practice activity

Create a price list dictionary for five products in SSP, let the user look up a product, and print 'not found' safely for unknown items.

Expected result: The lookup program returns prices for known products and a friendly message for unknown ones.

Check your understanding

  1. What happens if you use prices['rice'] and 'rice' is not a key?

    Show answer

    Python raises a KeyError.

  2. Which data structure would you use to store a student's name paired with their score?

    Show answer

    A dictionary, with the name as key and the score as value.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.