Reference library

Data pipelines & processing

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

9 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"
    …
15 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

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 medium

Enrich a stream with reference data by key lookup in Python

Uses streamz to join each incoming record to a reference dictionary by name, adding department and level fields or defaults.

streamz streaming join
Python
from streamz import Stream

reference = {"alice": {"dept": "eng", "level": 3}, "bob": {"dept": "sales", "level": 5}}

def enrich(record):
    name = record.get("name")
    ref = reference.get(name)
    joined = dict(record)
    if ref:
        joined.update(ref)
    else:
        joined["dept"] = "unknown"
        joi…
13 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 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 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 Reduce Aggregate Counts from Mapped Chunks in Python

Combine a list of mapped chunk dictionaries into a single aggregated count dictionary using functools.reduce.

reduce aggregation dictionary
Python
from functools import reduce
from collections import defaultdict

def aggregate_chunks(mapped_chunks):
    """Combine mapped chunk counts into a single aggregate dict."""
    return reduce(
        lambda acc, chunk: {
            **acc,
            **{k: acc.get(k, 0) + v for k, v in chunk.items()}
        },
       …
14 0 Open
Data pipelines & processing easy

Validate dict schema at pipeline boundary in Python

This code validates a dictionary against a TypedDict schema at a pipeline boundary, enforcing required fields and types with custom error messages.

validation dict typeddict
Python
from typing import Any, TypedDict


class Person(TypedDict):
    name: str
    age: int
    email: str


def validate_person(data: dict[str, Any]) -> Person:
    errors: list[str] = []

    if not isinstance(data.get("name"), str) or not data["name"].strip():
        errors.append("name must be a non-empty string")
  …
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.