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.
Python code
46 linesimport 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
{'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
- Use a generator instead of a list to avoid loading all data into memory at once.
- 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
More from Data pipelines & processing
- Add a UUID Surrogate Key to Each Row in a CSV with Python easy
- Attach Source File Metadata to Records in Python easy
- Build a Python Utility That Detects Duplicate Records Across Multiple Excel Sheets medium
- Check Null Rate Threshold in PySpark DataFrame medium
- Count Records Processed per Category in Python easy
- Create Data Helper Functions in Python for Beginners easy
Keep learning
Related tutorials and quizzes for this topic.