Reference library

Python Code Samples

Easy snippets you can copy, study, and run in the browser editor.

53 matches
Dictionaries & sets easy

Validate dictionary data with sets in Python

Validate a dictionary against required keys and allowed value sets, returning a list of validation errors.

dictionaries sets validation
Python
def validate_data(data, required_keys, allowed_values=None):
    """
    Validate a dictionary against required keys and optional allowed value sets.
    Returns a list of validation errors (empty list if valid).
    """
    errors = []
    
    # Check for missing required keys
    missing = set(required_keys) - set(…
14 0 Open
OOP & classes easy

How to Make a Python Class Hashable with __eq__ and __hash__

Define __eq__ and __hash__ together on a Python class so equal instances share the same hash and work correctly in sets and dictionary keys.

oop hashable eq
Python
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __eq__(self, other):
        if not isinstance(other, Point):
            return NotImplemented
        return self.x == other.x and self.y == other.y

    def __hash__(self):
        return hash((self.x, self.y))

    def __repr…
13 0 Open
Algorithms & data structures easy

Sort list by multiple keys with tuple ordering in Python

Sort a list of dictionaries by multiple criteria — surname, age, then score descending — using a tuple key and negation.

sorting tuples lambda
Python
def sort_multi_key(data):
    # Sorts by surname, then age, then score descending
    return sorted(
        data,
        key=lambda person: (
            person['surname'].lower(),
            person['age'],
            -person['score']  # negative to reverse sort by score
        )
    )


if __name__ == "__main__"…
14 0 Open
Algorithms & data structures easy

Stable sort preserving equal order demo in Python

Demonstrates Python's stable sort, showing that elements with equal sort keys retain their original relative order.

sorting stable sort timsort
Python
from operator import itemgetter

def stable_sort_demo():
    data = [(3, "first"), (1, "second"), (3, "third"), (1, "fourth"), (2, "fifth")]
    print("Original:", data)
    
    # Sort by first element (the tuple's first value), keeping relative order of equal items
    sorted_data = sorted(data, key=itemgetter(0))
 …
13 0 Open
Comprehensions & generators easy

Dict Comprehension to Map Keys to Lengths in Python

Build a dictionary that maps each word to its character count using a dictionary comprehension.

dictionary comprehension len
Python
words = ["apple", "banana", "cherry", "date", "elderberry"]

word_lengths = {word: len(word) for word in words}

print(word_lengths)
14 0 Open
Comprehensions & generators easy

Group Consecutive Keys in Python with itertools.groupby

Group consecutive equal elements in a list using the itertools.groupby generator, printing each key and its values.

itertools groupby generators
Python
from itertools import groupby

data = [1, 1, 2, 2, 3, 1, 1, 4, 4, 4]

for key, group in groupby(data):
    group_list = list(group)
    print(f"Key: {key}, Values: {group_list}")
11 0 Open
AI & LLM integration patterns easy

JSON Mode Prompt Schema Output in Python

Extract a user object to JSON with explicit schema keys, ready for LLM JSON-mode prompts.

json schema llm
Python
import json
from typing import Any, Dict


def extract_user_as_json(user: Dict[str, Any]) -> str:
    """Extract a user object and return it as JSON using explicit schema keys."""
    schema_fields = ("id", "name", "email", "is_active")
    user_subset = {key: user[key] for key in schema_fields if key in user}
    ret…
13 0 Open
Automation & scripting easy

Rotate API keys in Python by updating an .env template

Replace an old API key with a new one inside an .env template file, with a guard for missing keys.

api-keys env-files automation
Python
import json
from pathlib import Path

def rotate_api_keys(env_template_path: Path, old_key: str, new_key: str) -> None:
    """Replace an old API key with a new one in an .env template file."""
    content = env_template_path.read_text()
    if old_key not in content:
        print(f"Error: '{old_key}' not found in {e…
13 0 Open
Data pipelines & processing easy

ETL in Python: Extract CSV, Transform Dicts, Load JSON

Build a simple ETL pipeline that reads a CSV, normalizes keys and converts price to float, then writes structured JSON.

etl csv json
Python
import csv
import json
from pathlib import Path

def etl_csv_to_json(csv_path: str, json_path: str) -> None:
    """Extract CSV, transform rows to dicts, load to JSON."""
    with open(csv_path, mode='r', newline='', encoding='utf-8') as f:
        reader = csv.DictReader(f)
        records = list(reader)

    # Trans…
12 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

Test a Python Pipeline with Fixture Sample Rows

Test pipeline functions with sample rows provided by a pytest fixture, verifying required keys and value constraints.

pytest fixtures data-pipelines
Python
import pytest


def get_value(data: dict, key: str):
    return data.get(key)


def sample_rows():
    return [
        {"name": "Alice", "age": 30, "city": "London"},
        {"name": "Bob", "age": 25, "city": "Paris"},
        {"name": "Charlie", "age": 35, "city": "Berlin"},
    ]


@pytest.fixture
def sample_data(…
16 0 Open
Git + Python easy

Build a Simple Log Graph in Python

Create a basic one-dimensional bar chart from log lines by counting occurrences of leading numeric keys.

logging visualization graph
Python
import heapq


def log_graph(log_lines: list[str]) -> str:
    """Build a simple per-line, one-dimensional visual graph from log entries."""
    counts: dict[int, int] = {}
    for line in log_lines:
        tokens = line.split()
        if tokens:
            try:
                idx = int(tokens[0])
            exce…
16 0 Open
System design patterns easy

Route Messages to Handlers with a Python Dict

This code demonstrates a simple message routing pattern using a dictionary to map topic keys to handler functions, with a default handler for unmatched topics.

routing dictionary message-broker
Python
def route_message(message, routing_table):
    """Route a message to the correct handler based on the topic key."""
    topic = message.get("topic", "default")
    handler = routing_table.get(topic, routing_table.get("default"))
    return handler(message)


def handle_orders(message):
    return f"Orders handler proc…
12 0 Open
Streaming & messaging easy

Exactly Once Idempotent Consumer Store in Python

A mock key-value store that guarantees exactly-once processing by rejecting duplicate message keys in a message or event stream.

idempotency streaming deduplication
Python
from collections import defaultdict

class ExactlyOnceStore:
    def __init__(self):
        self.processed = defaultdict(set)
        self.data = {}

    def consume(self, key, value):
        if key in self.data:
            return False
        self.data[key] = value
        return True

    def get_processed_count…
15 0 Open
Streaming & messaging easy

How to mock RabbitMQ queue binding with routing keys in Python

A mock demonstration of binding a queue to an exchange with multiple routing keys in RabbitMQ using Python and pika, without a real broker connection.

rabbitmq messaging pika
Python
import pika
import sys


def bind_queue_with_routing(channel, queue_name, exchange_name, routing_keys):
    """
    Mock RabbitMQ queue binding with routing keys.
    Prints the binding configuration instead of connecting to a real broker.
    """
    for routing_key in routing_keys:
        binding = {
            "q…
14 0 Open
Caching & Redis easy

Cache Asides in Python with a Read-Through Loader

Implements a cache-aside pattern with a read-through loader that fetches missing keys from a backing data store and caches them.

caching cache-aside read-through
Python
class DataStore:
    """Mock database with a few records."""
    def __init__(self):
        self.data = {1: "Alice", 2: "Bob", 3: "Charlie"}

    def get(self, key):
        print(f"Loading key {key} from database")
        return self.data.get(key)


class CacheAsideLoader:
    """Cache-aside pattern with a read-thr…
16 0 Open
Caching & Redis easy

Cache Warming with Python: Preload Hot Keys

Demonstrates a simple LRU-like cache with a warm method that preloads hot keys with mock values using OrderedDict.

caching ordereddict lru
Python
import time
from collections import OrderedDict

class CacheWarm:
    def __init__(self, capacity=3):
        self.capacity = capacity
        self.cache = OrderedDict()
        self.hot_keys = []

    def warm(self, keys):
        """Preload hot keys into cache with mock values."""
        for key in keys:
          …
17 0 Open
Caching & Redis easy

How to Implement Namespaced Cache Keys for Tenant Isolation in Python

Build a tenant-aware cache wrapper that prefixes keys with tenant and namespace, and test it with mocks.

cache tenant namespace
Python
from keyvaluestore import SimpleCache
from unittest.mock import patch

class TenantCache(SimpleCache):
    def __init__(self, tenant_id, namespace="default"):
        super().__init__()
        self.tenant_id = tenant_id
        self.namespace = namespace

    def _key(self, key):
        return f"tenant:{self.tenant_…
17 0 Open
Caching & Redis easy

How to Iterate Redis Keys with SCAN in Python

Iterate all Redis keys matching a pattern using the SCAN command with a mock client to simulate pagination.

redis scan keys
Python
import redis

def scan_keys(client, pattern="*", count=10):
    keys = []
    cursor = 0
    while True:
        cursor, batch = client.scan(cursor=cursor, match=pattern, count=count)
        keys.extend(batch)
        if cursor == 0:
            break
    return keys

if __name__ == "__main__":
    # Mock Redis clien…
15 0 Open
Caching & Redis easy

How to use Redis MGET MSET pipeline in Python

Store multiple keys atomically and read them efficiently with Redis MSET/MGET, then batch commands with a pipeline to cut round trips.

redis mget mset
Python
import redis  # v4.x+ required

r = redis.Redis(host="localhost", port=6379, db=0, decode_responses=True)

# Sample data to store
r.flushdb()
data = {"name": "Alice", "age": "30", "city": "Berlin"}

# MSET: store multiple key-value pairs in one command
r.mset(data)

# MGET: fetch multiple keys in one round trip
keys =…
15 0 Open
Observability & SRE easy

How to Mock a Baggage Context (Key-Value Store) in Python

This code implements an in-memory key-value mock of a baggage context, letting you set, get, check, and delete keys for tracing-style metadata.

baggage tracing mock
Python
class BaggageContext:
    def __init__(self):
        self._store = {}

    def set(self, key, value):
        self._store[key] = value
        return value

    def get(self, key, default=None):
        return self._store.get(key, default)

    def has(self, key):
        return key in self._store

    def delete(sel…
15 0 Open
Observability & SRE easy

How to Redact Secrets from Log Messages in Python

Build a lightweight RedactingFormatter class that replaces sensitive tokens like passwords and API keys with [REDACTED] before log messages are printed.

redaction logging secrets
Python
class RedactingFormatter:
    def __init__(self, secrets):
        self.secrets = secrets

    def redact(self, message):
        for secret in self.secrets:
            message = message.replace(secret, "[REDACTED]")
        return message

    def format(self, record):
        message = record["message"]
        ret…
12 0 Open
Microservices patterns easy

How to Implement an Exactly-Once Deduplication Store in Python

Implement a Python class that deduplicates keys exactly once, tracking first-seen timestamps and duplicate counts.

deduplication exactly-once set
Python
from datetime import datetime
from typing import Any, Hashable


class ExactlyOnceStore:
    def __init__(self) -> None:
        self._seen: set[Hashable] = set()
        self._first_seen: dict[Hashable, datetime] = {}
        self._counts: dict[Hashable, int] = {}

    def add(self, key: Hashable, value: Any = None) …
13 0 Open
Big data & Spark easy

Modeling a Hive Metastore Table Schema in Python

A dataclass that mimics a Hive metastore table schema—columns, partition keys, storage format, and location—with helper methods for description and mutation.

hive dataclass metastore
Python
from dataclasses import dataclass, field
from typing import Dict, List, Optional


@dataclass
class HiveTable:
    """Simple mock of a Hive metastore table schema."""
    name: str
    database: str = "default"
    columns: List[Dict[str, str]] = field(default_factory=list)
    partition_keys: List[Dict[str, str]] = f…
14 0 Open

Browse by section

Each section groups closely related Python snippets.

Guide: free Python code samples library

Copy-ready Python snippets for learners and developers

PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.

How to use this library

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. Run it in the IDE, tweak values, then take a related quiz or tutorial lesson

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.