Back to Blog
Lesson 17 of the Python: Programming from Zero with Python course
PythonAugust 3, 20264 min read

Project: Statistics Processor | Python Beginner Course

Learn to store data in lists of dictionaries and calculate summary statistics in this hands-on Python project lesson.

pythonprojectprogrammingfunctionsdata processing
Hands interacting with charts and notes for data analysis on a desk.

Previously in this course, we covered defining custom functions and working with lists and dictionaries. Now, we are going to combine those concepts to build a Statistics Processor.

Instead of just collecting one piece of data, we will design a CLI tool that accepts multiple entries, stores them in a structured format, and provides an automated report.

Moving from Single Inputs to Data Collections

In our previous Project: The Data Collector CLI Tool for Python Beginners, we captured data and displayed it immediately. However, real-world applications rarely process data one item at a time. They collect a batch of entries and then perform analysis.

To handle this, we will use a list of dictionaries. Each dictionary represents a single entry (e.g., a "score" or "measurement"), and the list acts as our in-memory database.

The Data Structure Strategy

Using a list of dictionaries allows us to scale our data. If we want to add more fields later (like a timestamp or user ID), we simply add a new key-value pair to the dictionary without breaking our existing logic.

Worked Example: Building the Processor

Detailed view of hands installing a CPU onto a motherboard inside a computer setup.

Let’s build a tool that collects multiple test scores and calculates their average.

PYTHON
def calculate_average(scores_list):
    if not scores_list:
        return 0
    total = sum(scores_list)
    return total / len(scores_list)

def run_processor():
    data_store = []
    
    while True:
        entry = input("Enter a score(or CE9178">'done' to finish): ")
        if entry.lower() == CE9178">'done':
            break
        
        # Storing data as a dictionary
        record = {"score": float(entry)}
        data_store.append(record)
        
    # Extracting scores for calculation
    scores = [item["score"] for item in data_store]
    avg = calculate_average(scores)
    
    print(f"--- Summary Stats ---")
    print(f"Total entries: {len(data_store)}")
    print(f"Average score: {avg:.2f}")

# Start the program
run_processor()

Breakdown of the Code

  1. data_store = []: We initialize an empty list to hold our dictionary objects.
  2. while True: This loop allows us to keep collecting data until the user explicitly signals they are finished.
  3. List Comprehension: The line [item["score"] for item in data_store] is a concise way to create a new list containing only the values associated with the "score" key.
  4. calculate_average: By passing the extracted list to this function, we keep our calculation logic separate from our user interface logic.

Hands-on Exercise

Modify the code above to track more than just a score.

  1. Update the record dictionary to include a "name" field (input from the user).
  2. Add a new function called display_all_entries that iterates through your data_store and prints every name and score in a formatted table.
  3. Add a check to ensure the average calculation doesn't crash if the list is empty (we've already handled this in the example above, but ensure you understand why if not scores_list: is necessary).

Common Pitfalls

Close-up of a rusty sewer manhole cover in a grassy Boston park.

  • Division by Zero: If your list is empty, len(scores_list) is zero. Always check if the list has elements before dividing.
  • Data Types: Input from the console is always a string. If you forget to cast it to float() or int() before storing it, your sum() function will raise a TypeError.
  • Scope Issues: Ensure your data_store list is defined in a scope accessible to the parts of your program that need to read it. If you define it inside the while loop, it will be reset every time the loop repeats.

FAQ

Why use a list of dictionaries instead of just a list of numbers? Dictionaries allow you to attach metadata to your data points. Storing {"score": 90, "user": "Alice"} is much more flexible than just storing 90.

What if I want to save this data permanently? For now, the data lives only in your computer's RAM. In future lessons, we will cover how to write this data to files to ensure it persists after the program closes.

Recap

Team members presenting a project in a modern office setting with a focus on collaboration.

We successfully built a data processing tool by:

  • Creating a storage structure using a list of dictionaries.
  • Using functions to encapsulate the data processing logic (calculating the average).
  • Handling user input loops to allow for dynamic, multi-entry collection.

This modular approach is the foundation for building larger, more complex CLI tools.

Up next: Learn how to persist your data across sessions in Reading Files.

Similar Posts