Python & data · Lesson 13
Build a small data summary
Combine lists, dictionaries, loops, and functions to answer a question about a small dataset.
- Read a small collection of records
- Compute a total and average
- Handle an empty collection
Helpful background: Understand loops, functions, lists, and dictionaries.
Start with a question
Suppose you want to know how many visitors came to a park over three days. Each dictionary represents one day, and each visitors value is a non-negative count.
Real datasets can contain missing or invalid values. This small example assumes each record has a visitors key holding a number.
days = [
{"day": "Monday", "visitors": 12},
{"day": "Tuesday", "visitors": 18},
{"day": "Wednesday", "visitors": 15},
]
print(len(days)) # 3Calculate a total
Start at zero and add each record's visitors value. For these three days, the total is 45.
Put reusable logic in a function so you can try it with other collections.
def total_visitors(records):
total = 0
for record in records:
total += record["visitors"]
return total
sample = [{"visitors": 12}, {"visitors": 18}, {"visitors": 15}]
print(total_visitors(sample)) # 45Calculate an average safely
An average is the total divided by the number of records. Dividing by zero raises ZeroDivisionError, so decide what an empty collection should mean before calculating.
This example returns None when there are no records. A caller can then show a helpful message instead of treating missing data as zero.
def average_visitors(records):
if not records:
return None
total = sum(record["visitors"] for record in records)
return total / len(records)
print(average_visitors([{"visitors": 12}, {"visitors": 18}])) # 15.0
print(average_visitors([])) # NoneExplain the result
A useful summary answers the question and mentions what the data does not show. Three days do not establish a long-term trend, and an average alone does not explain why the counts changed.
Try a different set of counts, a single record, and an empty list. Check your result by hand before trusting the program.
Why does average_visitors check for an empty list?
Your turn
Add a fourth day with 20 visitors to the first dataset and calculate the new total.
days = [ {"day": "Monday", "visitors": 12}, {"day": "Tuesday", "visitors": 18}, {"day": "Wednesday", "visitors": 15}, ] days.append({"day": "Thursday", "visitors": 20}) print(sum(day["visitors"] for day in days)) # 65
BUILT TOGETHER
Help make this explanation better.
Have a clearer explanation, a useful example, or a correction? Share it with the community.
Be the first to add your name when you improve this lesson.
How to get credited