Reference library

Data pipelines & processing

ETL-style flows, batch transforms, validation, and moving data between formats.

42 matches
Data pipelines & processing easy

Attach Source File Metadata to Records in Python

Add a source filename field to each record in a list by merging a new key into every dictionary using a dict unpacking comprehension.

lineage metadata dict-unpacking
Python
from pathlib import Path
import json

def attach_source_metadata(records, source_file):
    """Attach source filename metadata to each record."""
    return [
        {**record, "source": Path(source_file).name}
        for record in records
    ]

if __name__ == "__main__":
    source = "/data/raw/customers.csv"
    …
16 0 Open
Data pipelines & processing easy

Count Records Processed per Category in Python

Use a Counter dictionary to track how many records of each type (ok, error, retry) were processed in a data pipeline.

counter metrics data-pipeline
Python
from collections import Counter
import random

processed_counter = Counter()

def process_records(records):
    for record in records:
        processed_counter[record] += 1
    return len(records)

if __name__ == "__main__":
    sample_records = [random.choice(["ok", "error", "retry"]) for _ in range(10)]
    print(f…
15 0 Open
Data pipelines & processing easy

Create Data Helper Functions in Python for Beginners

Build reusable Python helper functions to load, filter, sort, summarize, and save JSON data — a beginner-friendly starting point for small data pipelines.

json pipeline helpers
Python
import json
from pathlib import Path
from typing import Any, Dict, List


def load_json_file(filepath: str) -> Dict[str, Any]:
    """Load JSON data from a file."""
    with Path(filepath).open("r", encoding="utf-8") as file:
        return json.load(file)


def filter_by_key(
    data: List[Dict[str, Any]], key: str,…
14 0 Open
Data pipelines & processing easy

Enrich Events with Geo IP Data in Python

Returns a copy of each event dictionary, enriched with a geo-location dict from a mock IP-to-geo lookup table, with a fallback for unknown IPs.

data-enrichment dictionaries pipelines
Python
import ipaddress


GEO_IP_DB = {
    "192.168.1.10": {"country": "US", "city": "New York", "lat": 40.7128, "lon": -74.0060},
    "10.0.0.5": {"country": "DE", "city": "Berlin", "lat": 52.5200, "lon": 13.4050},
    "172.16.0.8": {"country": "JP", "city": "Tokyo", "lat": 35.6762, "lon": 139.6503},
}

EVENTS = [
    {"id…
14 0 Open
Data pipelines & processing easy

Filter Records by Required Fields in Python

Filter a list of dictionaries, keeping only records where every required field is present and not None.

filter data-cleaning pipelines
Python
def filter_records(records, required_fields):
    """Return only records that have all required fields non-null."""
    return [
        record for record in records
        if all(record.get(field) is not None for field in required_fields)
    ]


if __name__ == "__main__":
    sample_records = [
        {"name": "Al…
14 0 Open
Data pipelines & processing easy

Generate a Deterministic Hash for Deduplication in Python

Create a stable SHA-256 fingerprint from nested data and file contents to deduplicate records in a data pipeline.

hashing deduplication sha256
Python
import hashlib
import json
from pathlib import Path

def natural_key_hash(data, salt=""):
    """
    Generate a deterministic fingerprint from raw data (dict/list/str).
    Uses JSON canonical-ish serialization with sorted keys and SHA-256.
    """
    canonical = json.dumps(data, sort_keys=True, separators=(",", ":"…
15 0 Open
Data pipelines & processing easy

Generate a Mock CDC Changelog in Python

Simulate a CDC changelog with INSERT, UPDATE, and DELETE operations, timestamps, and record snapshots for testing data pipelines.

cdc changelog mock-data
Python
import json
from datetime import datetime, timedelta


def generate_mock_changelog(records, operations=("INSERT", "UPDATE", "DELETE")):
    """Simulate a CDC changelog from a list of record snapshots."""
    base_time = datetime(2025, 1, 1, 8, 0, 0)
    changelog = []
    for idx, record in enumerate(records):
       …
15 0 Open
Data pipelines & processing easy

Group Python Events into Sessions with a Gap Timeout

Groups timestamped events into sessions, starting a new session when the time gap exceeds a specified timeout.

sessions grouping datetime
Python
from itertools import groupby
from datetime import datetime, timedelta

def session_window_group(events, gap_seconds=300):
    """Group events into sessions where gap > gap_seconds starts a new session."""
    if not events:
        return []
    
    events = sorted(events, key=lambda x: x[0])
    sessions = []
    c…
13 0 Open
Data pipelines & processing easy

How to Build Data Processing Functions in Python

Create reusable helper functions to load, filter, transform, and aggregate CSV data in Python.

csv pipeline etl
Python
import csv
from pathlib import Path


def load_data(filepath):
    """Load CSV data into a list of dicts."""
    with open(filepath, "r", newline="", encoding="utf-8") as f:
        return list(csv.DictReader(f))


def filter_rows(rows, column, value):
    """Keep rows where column equals value."""
    return [row for…
11 0 Open
Data pipelines & processing easy

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.

pipeline json aggregation
Python
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]:
    """Kee…
10 0 Open
Data pipelines & processing easy

How to Clean and Format Data in Python

This code loads JSON data, cleans records by removing empty fields and normalizing text, then summarizes the results with counts and unique keys.

json data cleaning data pipelines
Python
import json
from pathlib import Path


def load_data(filepath: str) -> dict:
    """Load JSON data from a file."""
    with Path(filepath).open("r", encoding="utf-8") as f:
        return json.load(f)


def clean_records(records: list[dict]) -> list[dict]:
    """Remove empty fields and normalize text to lowercase."""…
13 0 Open
Data pipelines & processing easy

How to Compress Pipeline Output Gzip Per Partition in Python

Compress each partition of pipeline output into a separate gzip file and verify the compressed data by reading it back.

gzip compression pipeline
Python
import gzip
import io
import random
from pathlib import Path


def compress_partition(partition_data: list[str], output_path: Path) -> int:
    """Compress a partition of data to a gzip file, returns bytes written."""
    with gzip.open(output_path, 'wt', encoding='utf-8') as f:
        f.writelines(partition_data)
  …
13 0 Open
Data pipelines & processing easy

How to Convert Data Types in a Python Data Pipeline

Demonstrates a simple Python data pipeline that converts string values to proper types (bool, int, float, datetime) and outputs structured JSON.

data-pipeline type-conversion json
Python
import json
from datetime import datetime

def convert_value(value):
    """Convert string values to appropriate Python types."""
    if value.lower() == "true":
        return True
    if value.lower() == "false":
        return False
    if value.isdigit():
        return int(value)
    try:
        return float(val…
11 0 Open
Data pipelines & processing easy

How to Count JSON Records in Python

Read a JSON file and count the number of top-level records, handling both list and dictionary structures.

json counting file-reading
Python
import json
from pathlib import Path

def count_records(json_file):
    """Count top-level records in a JSON file."""
    with open(json_file, "r") as f:
        data = json.load(f)
    
    # Handle both list of records and dict of records
    if isinstance(data, list):
        return len(data)
    elif isinstance(da…
12 0 Open
Data pipelines & processing easy

How to Deduplicate Events with At-Least-Once Delivery in Python

Implements an exactly-once processing pattern for at-least-once event delivery by tracking seen event IDs in a set, skipping duplicates.

deduplication idempotent event-processing
Python
seen_ids = set()

def process_event(event_id: str, payload: dict) -> dict:
    """Process an event exactly once, ignoring duplicates."""
    if event_id in seen_ids:
        return {"status": "duplicate", "event_id": event_id}
    seen_ids.add(event_id)
    return {"status": "processed", "event_id": event_id, **payloa…
13 0 Open
Data pipelines & processing easy

How to Explode an Array Field into Multiple Rows in Python

This code flattens a list of dictionaries by exploding each array field value into its own row, duplicating the other fields as needed.

data transformation arrays flattening
Python
from collections import defaultdict

data = [
    {"id": 1, "name": "Alice", "tags": ["python", "data", "ai"]},
    {"id": 2, "name": "Bob", "tags": ["web", "devops"]},
    {"id": 3, "name": "Carol", "tags": []},
]

def explode_array_field(records, array_field):
    result = []
    for record in records:
        for v…
11 0 Open
Data pipelines & processing easy

How to Filter Data in Python

Filter a list of dictionaries by exact key-value matches or numerical ranges using concise list comprehensions.

filtering list-comprehension dictionaries
Python
from typing import List, Dict, Any


def filter_data(
    data: List[Dict[str, Any]], key: str, value: Any
) -> List[Dict[str, Any]]:
    """Return records where data[key] equals value."""
    return [record for record in data if record.get(key) == value]


def filter_by_range(
    data: List[Dict[str, Any]], key: str…
12 0 Open
Data pipelines & processing easy

How to Group Data by Key in Python

Group a list of dictionaries by a specified key using a defaultdict and compute per-group averages.

grouping defaultdict data-pipelines
Python
from collections import defaultdict

def group_by_key(data, key):
    grouped = defaultdict(list)
    for item in data:
        grouped[item[key]].append(item)
    return dict(grouped)

if __name__ == "__main__":
    records = [
        {"name": "Alice", "dept": "Engineering", "score": 85},
        {"name": "Bob", "de…
15 0 Open
Data pipelines & processing easy

How to Group Rows by Key into Nested Arrays in Python

This code groups rows in a list of dictionaries by a specified key and returns a dictionary with each key mapped to a list of values from another key.

grouping defaultdict data-aggregation
Python
from collections import defaultdict


def implode_rows(rows, key, value_key):
    grouped = defaultdict(list)
    for row in rows:
        grouped[row[key]].append(row[value_key])
    return dict(grouped)


if __name__ == "__main__":
    data = [
        {"category": "fruit", "item": "apple"},
        {"category": "fr…
14 0 Open
Data pipelines & processing easy

How to Hash Email Addresses in a PII Masking Pipeline in Python

Replaces every email address in a text string with its SHA-256 hash to protect personally identifiable information (PII).

pii hashing sha256
Python
import hashlib
import re

def hash_email(email: str) -> str:
    """Mask an email address by hashing it with SHA-256."""
    normalized = email.strip().lower()
    return hashlib.sha256(normalized.encode("utf-8")).hexdigest()

def mask_pii_emails(text: str) -> str:
    """Replace all email addresses in text with their…
14 0 Open
Data pipelines & processing easy

How to Merge Incremental Snapshot Upsert Dict in Python

Merge a snapshot dict into a base dict, recursively updating nested dictionaries while preferring snapshot values on conflicts.

dict merge upsert
Python
def merge_upsert(base: dict, snapshot: dict) -> dict:
    """
    Merge a snapshot dict into a base dict, preferring snapshot values 
    on key conflicts (upsert semantics). Nested dicts are merged recursively.
    """
    result = dict(base)
    
    for key, value in snapshot.items():
        if key in result and i…
13 0 Open
Data pipelines & processing easy

How to Merge Multiple Data Sources in Python

A beginner-friendly helper that merges lists of dictionaries from multiple sources into one combined list using key filtering.

merge pipelines dicts
Python
import json

def merge_pipeline_data(*data_sources, keys=()):
    """Merge multiple data sources (list of dicts) into a single list of merged dicts.
    
    Args:
        *data_sources: One or more lists of dictionaries.
        keys: Tuple of keys to include from each source (empty means all keys).
    Returns:
    …
14 0 Open
Data pipelines & processing easy

How to Partition Output Files by Date Key in Python

Group output files into a dictionary partitioned by a YYYYMMDD date key extracted from the filename prefix.

file-partitioning date-key pathlib
Python
from pathlib import Path
from collections import defaultdict

def partition_files_by_date(directory: str) -> dict:
    """Partition output files by date key extracted from filename (YYYYMMDD prefix)."""
    path = Path(directory)
    partitions = defaultdict(list)
    
    for file in path.iterdir():
        if file.i…
14 0 Open
Data pipelines & processing easy

How to Process CSV Data in Python with a Data Helper

Build a beginner-friendly data helper in Python that loads a CSV file, filters rows by a condition, and summarizes numeric fields.

csv data-processing pathlib
Python
import csv
from pathlib import Path

DATA = [
    {"name": "Alice", "score": 88, "passed": True},
    {"name": "Bob", "score": 42, "passed": False},
    {"name": "Carol", "score": 95, "passed": True},
]


def load_csv(file_path: Path) -> list[dict]:
    with file_path.open(newline="", encoding="utf-8") as f:
        r…
13 0 Open

Browse by section

Each section groups closely related Python snippets.

Data pipelines & processing — Python code examples

What you will find here

This page collects data pipelines & processing snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.