How to Build a Simple Data Pipeline in Python

A beginner-friendly data pipeline that loads JSON, filters records by a field value, and aggregates counts per category.

Easy Python 3.9+ Aug 9, 2026 Data pipelines & processing 11 views 0 copies

Python code

46 lines
Python 3.9+
import json
from pathlib import Path


def load_json(filepath: str | Path) -> list[dict]:
    """Load a JSON file containing a list of records."""
    with Path(filepath).open("r", encoding="utf-8") as f:
        return json.load(f)


def filter_records(records: list[dict], field: str, value) -> list[dict]:
    """Keep records where the given field exactly equals value."""
    return [r for r in records if r.get(field) == value]


def aggregate_count(records: list[dict], group_by: str) -> dict[str, int]:
    """Count records per unique value of group_by field."""
    counts: dict[str, int] = {}
    for record in records:
        key = record.get(group_by)
        counts[key] = counts.get(key, 0) + 1
    return counts


def pipeline(filepath: str | Path, filter_field: str, filter_value, group_by: str) -> dict[str, int]:
    """Run a complete mini pipeline: load → filter → aggregate."""
    data = load_json(filepath)
    filtered = filter_records(data, filter_field, filter_value)
    return aggregate_count(filtered, group_by)


if __name__ == "__main__":
    # Sample data written to a temp file for demonstration
    sample = [
        {"city": "Berlin", "status": "active"},
        {"city": "Munich", "status": "active"},
        {"city": "Berlin", "status": "inactive"},
        {"city": "Hamburg", "status": "active"},
    ]
    temp_file = Path("sample_data.json")
    temp_file.write_text(json.dumps(sample), encoding="utf-8")

    result = pipeline(temp_file, "status", "active", "city")
    print(result)

    temp_file.unlink()

Output

stdout
{'Berlin': 2, 'Munich': 1, 'Hamburg': 1}

How it works

This works by chaining three small pure functions: load_json reads the file, filter_records filters a list of dicts with a list comprehension, and aggregate_count counts values per key using a dictionary. The pipeline function composes these steps, making the flow easy to test and reuse. Using pathlib.Path for file handling ensures correct path handling across operating systems.

Common mistakes

  • Forgetting to pass encoding='utf-8' when opening files, which can cause UnicodeDecodeError.
  • Using `.get()` without a default and then crashing when a key is missing.
  • Expecting the output to be ordered, but Python dicts since 3.7 maintain insertion order, which matches the order records appear.
  • Writing temp files without cleanup, leaving artifacts on disk.

Variations

  1. Use a generator instead of a list to avoid loading all data into memory at once.
  2. Replace the aggregation with `collections.Counter` for the same result in one line.

Real-world use cases

  • Filtering event logs by severity and counting occurrences per service for monitoring dashboards.
  • Reading customer records, keeping only paying users, and grouping revenue by region.
  • Processing exported survey data and counting responses by category for weekly reports.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Data pipelines & processing

Related tutorials and quizzes for this topic.