Module 2 of 6 · 45 minutes

Data structures, logic and functions

Real data comes in collections. This module gives you the tools to store, loop over and make decisions about it.

By · Last updated

Learning objectives

  • Create, index and slice lists
  • Use dictionaries — the same shape as JSON
  • Write if/elif/else conditions
  • Loop with for, enumerate and list comprehensions
  • Define and call functions
  • Filter, total, sort and group a list of dictionaries
  • Write functions with default values and docstrings

2.1 Lists

reviews = ["Love it", "Arrived damaged", "Great value", "Too small"]
print(reviews[0])        # first item: "Love it"
print(reviews[-1])       # last item: "Too small"
print(len(reviews))      # 4
reviews.append("Would buy again")
print(reviews[1:3])      # slice: ["Arrived damaged", "Great value"]
"Love it"0-4"Arrived damaged"1-3"Great value"2-2"Too small"3-1indexfrom endreviews[0] → "Love it" reviews[-1] → "Too small" reviews[1:3] → middle two
List positions count from 0 at the front and from −1 at the back. Slices take a range.

2.2 Dictionaries

A dictionary maps keys to values — the same shape as JSON, which is how AI APIs send and receive data.

order = {"id": "GFY-10422", "item": "Bamboo board", "qty": 2, "price": 24.99}
print(order["item"])                 # "Bamboo board"
order["status"] = "dispatched"       # add a key
total = order["qty"] * order["price"]
print(total)                         # 49.98
print(order.get("discount", 0))      # safe lookup with a default: 0
keysvalues"id""GFY-10422""item""Bamboo board""qty"2"price"24.99order["item"] → "Bamboo board"
A dictionary maps keys to values — exactly the shape of the JSON that AI APIs send and receive.

2.3 Conditions

rating = 2
if rating >= 4:
    sentiment = "positive"
elif rating == 3:
    sentiment = "neutral"
else:
    sentiment = "negative"
print(sentiment)

Indentation (four spaces) matters in Python: it shows which lines belong to the if. Try changing rating and running the cell again.

2.4 Loops

for review in reviews:
    print(review.upper())

# loop with a counter
for i, review in enumerate(reviews, start=1):
    print(i, review)

# list comprehension: build a new list in one line
lengths = [len(r) for r in reviews]
short = [r for r in reviews if len(r) < 12]
print(lengths)
print(short)

2.5 Functions

Functions package code you'll reuse. You'll write one later to call an AI model.

def classify_rating(rating):
    # Return a sentiment label for a 1-5 star rating.
    if rating >= 4:
        return "positive"
    if rating == 3:
        return "neutral"
    return "negative"

ratings = [5, 2, 3, 4, 1]
labels = [classify_rating(r) for r in ratings]
print(labels)    # ['positive', 'negative', 'neutral', 'positive', 'negative']

2.6 Lists of dictionaries: how real data arrives

Put the two structures together and you have the shape of almost all the data you'll meet: a list of records, each one a dictionary. It is what a spreadsheet becomes when loaded, and what an API sends back.

orders = [
    {"id": "GFY-10422", "customer": "Asha",  "total": 49.98, "status": "dispatched"},
    {"id": "GFY-10423", "customer": "Ben",   "total": 12.00, "status": "pending"},
    {"id": "GFY-10424", "customer": "Asha",  "total": 31.50, "status": "dispatched"},
    {"id": "GFY-10425", "customer": "Chloe", "total": 86.20, "status": "returned"},
]

print(len(orders), "orders")
print(orders[0]["customer"])                                        # first order's customer

dispatched = [o for o in orders if o["status"] == "dispatched"]     # filter
print("Dispatched:", [o["id"] for o in dispatched])

print("Revenue: £", round(sum(o["total"] for o in orders), 2))      # add up one field

biggest = max(orders, key=lambda o: o["total"])                     # the largest by a field
print("Biggest order:", biggest["id"], biggest["total"])

for o in sorted(orders, key=lambda o: o["total"], reverse=True):    # sort by a field
    print(f"  {o['id']}  £{o['total']:>6.2f}  {o['customer']}")

key=lambda o: o["total"] reads as "to compare two orders, look at their total". A lambda is a small function written in place; you'll see it wherever something needs to be sorted or ranked.

2.7 Counting and grouping

The commonest question to ask of a list of records is "how many, or how much, per something?" The pattern is a dictionary that you build up as you loop.

spend = {}                                   # customer -> total spent
for o in orders:
    name = o["customer"]
    spend[name] = spend.get(name, 0) + o["total"]     # start from 0 the first time
print({name: round(total, 2) for name, total in spend.items()})

from collections import Counter              # counting is so common that Python has a tool for it
print(Counter(o["status"] for o in orders))

In Module 4 pandas will do this in one line with groupby. It is worth writing it by hand once, because the loop is what pandas is doing for you — and because small jobs often don't need pandas at all.

2.8 Functions that are easy to reuse

def order_summary(order, currency="£", show_status=True):
    """Return a one-line description of an order."""
    line = f"{order['id']}: {currency}{order['total']:.2f} for {order['customer']}"
    if show_status:
        line += f" ({order['status']})"
    return line

print(order_summary(orders[0]))                       # uses the defaults
print(order_summary(orders[1], currency="€"))         # override one, by name
print(order_summary(orders[3], show_status=False))

Three habits make a function pleasant to come back to: default values for settings that rarely change, a one-line docstring (the text in triple quotes) saying what it returns, and returning the result instead of printing it, so the caller decides what to do with it.

rating = 2classify_rating(rating)if ≥ 4 → positive3 → neutral, else negative"negative"inputreturn
A function takes inputs, runs its logic, and returns a result you can reuse anywhere.
Exercise: count the complaints

Given a list of review dictionaries like {"text": "Arrived damaged", "stars": 1}, write a function that returns how many reviews have 2 stars or fewer, and a list of their texts.

Your turnstar_reviews = [
    {"text": "Love it", "stars": 5},
    {"text": "Arrived damaged", "stars": 1},
    {"text": "Too small", "stars": 2},
]

# Write your function here, then press Run
Show a solution
star_reviews = [
    {"text": "Love it", "stars": 5},
    {"text": "Arrived damaged", "stars": 1},
    {"text": "Too small", "stars": 2},
]

def complaints(items):
    bad = [r["text"] for r in items if r["stars"] <= 2]
    return len(bad), bad

print(complaints(star_reviews))   # (2, ['Arrived damaged', 'Too small'])
Exercise: the top customer

Using a list of orders like the one in 2.6, write a function top_customer(orders) that returns the name of the customer who has spent the most in total, and the amount. Ignore orders whose status is "returned".

Your turnshop_orders = [
    {"id": "GFY-10422", "customer": "Asha",  "total": 49.98, "status": "dispatched"},
    {"id": "GFY-10423", "customer": "Ben",   "total": 12.00, "status": "pending"},
    {"id": "GFY-10424", "customer": "Asha",  "total": 31.50, "status": "dispatched"},
    {"id": "GFY-10425", "customer": "Chloe", "total": 86.20, "status": "returned"},
]

# Write top_customer(order_list), try it on shop_orders, then press Run
Show a solution
shop_orders = [
    {"id": "GFY-10422", "customer": "Asha",  "total": 49.98, "status": "dispatched"},
    {"id": "GFY-10423", "customer": "Ben",   "total": 12.00, "status": "pending"},
    {"id": "GFY-10424", "customer": "Asha",  "total": 31.50, "status": "dispatched"},
    {"id": "GFY-10425", "customer": "Chloe", "total": 86.20, "status": "returned"},
]

def top_customer(order_list):
    spend = {}
    for o in order_list:
        if o["status"] != "returned":
            spend[o["customer"]] = spend.get(o["customer"], 0) + o["total"]
    name = max(spend, key=spend.get)
    return name, round(spend[name], 2)

print(top_customer(shop_orders))     # ('Asha', 81.48)

Key takeaways

  • Lists hold ordered items; index from 0, and -1 is the last.
  • Dictionaries map keys to values, like JSON.
  • Indentation defines code blocks.
  • List comprehensions build lists concisely.
  • Functions package reusable logic.
  • A list of dictionaries is the shape most real data arrives in.
  • Return results from functions instead of printing them, and give rarely changed settings defaults.