Reference library

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

315 matches
Strings & text easy

Find Most Frequent Character in a String in Python

Count character frequencies in a Python string using a dictionary and return the character that appears most often with a max() key function.

string dictionary counting
Python
def most_frequent_char(s: str) -> str:
    if not s:
        return ""
    
    char_count = {}
    for ch in s:
        char_count[ch] = char_count.get(ch, 0) + 1
    
    max_char = max(char_count, key=char_count.get)
    return max_char

if __name__ == "__main__":
    text = "programming"
    result = most_frequent…
12 0 Open
Strings & text easy

How to Format Strings with Named Placeholders in Python

Format a template string using named placeholders with the str.format() method and a dictionary.

string format placeholders
Python
def format_named(template, data):
    """Format a template string using named placeholders."""
    return template.format(**data)


if __name__ == "__main__":
    template = "Hello {name}, you are {age} years old and live in {city}."
    data = {"name": "Alice", "age": 30, "city": "London"}
    result = format_named(t…
15 0 Open
Strings & text easy

How to Group Data by Category in Python

Group a list of (category, value) tuples into a dictionary of lists using the setdefault method.

grouping dictionaries setdefault
Python
def group_by_category(data):
    """Group list of (category, value) tuples into dictionaries of lists."""
    groups = {}
    for category, value in data:
        groups.setdefault(category, []).append(value)
    return groups

if __name__ == "__main__":
    items = [
        ("fruit", "apple"),
        ("veg", "carro…
12 0 Open
Strings & text easy

How to Validate Text Input in Python: A Simple Text Processor

A Python function that validates a text string by trimming whitespace, then returns a dictionary with character, word, and sentence counts.

text-validation strings input-checking
Python
def validate_text(text: str) -> dict:
    """Analyze a text string and return basic validation statistics."""
    stripped = text.strip()
    if not stripped:
        return {
            "valid": False,
            "reason": "Text is empty or only whitespace",
            "characters": 0,
            "words": 0,
    …
11 0 Open
Strings & text easy

How to parse key=value pairs in Python

Parse a single line of key=value pairs separated by a delimiter into a Python dictionary.

parsing key-value dictionary
Python
def parse_key_value_pairs(line: str, delimiter: str = "&") -> dict:
    """Parse a single line of key=value pairs into a dictionary."""
    pairs = {}
    for token in line.split(delimiter):
        if not token.strip():
            continue
        key, _, value = token.partition("=")
        pairs[key.strip()] = val…
11 0 Open
Lists & loops easy

How to Build a Frequency Map from a List in Python

This code builds a dictionary that maps each unique element in a list to its count using the Counter class from the collections module.

counter frequency dictionary
Python
from collections import Counter

def build_frequency_map(values):
    """Return a dictionary mapping each unique value to its frequency."""
    return dict(Counter(values))

if __name__ == "__main__":
    data = ["apple", "banana", "apple", "cherry", "banana", "apple"]
    freq_map = build_frequency_map(data)
    prin…
13 0 Open
Lists & loops easy

How to Sort a List of Dictionaries by a Key in Python

Sort a list of dictionaries by a specified key field, optionally in descending order, using Python's built-in sorted() function.

sort dictionaries list
Python
def sort_dicts_by_key(data, key, reverse=False):
    return sorted(data, key=lambda item: item.get(key), reverse=reverse)


if __name__ == "__main__":
    people = [
        {"name": "Alice", "age": 30},
        {"name": "Bob", "age": 25},
        {"name": "Charlie", "age": 35},
    ]

    sorted_by_age = sort_dicts_b…
14 0 Open
Lists & loops easy

How to Summarize a List of Numbers in Python

Loop over a list of numbers to compute total, count, average, min, and max, then return them in a dictionary.

lists loops statistics
Python
def summarize_numbers(numbers):
    """Return a dict with basic stats for a list of numbers."""
    total = 0
    count = 0
    smallest = numbers[0]
    largest = numbers[0]

    for num in numbers:
        total += num
        count += 1
        if num < smallest:
            smallest = num
        if num > largest:…
16 0 Open
Functions & basics easy

How to Load a .env File Manually in Python

Parse a .env-style key-value file into a Python dictionary using only the standard library, with comment and quoted-value handling.

dotenv environment-variables file-parsing
Python
import re
from pathlib import Path


def load_dotenv_file(filepath: str) -> dict[str, str]:
    """Parse a .env-style file into a dictionary."""
    env = {}
    path = Path(filepath)

    if not path.exists():
        raise FileNotFoundError(f"Environment file not found: {filepath}")

    for line in path.read_text()…
13 0 Open
Functions & basics easy

How to Sort a List of Dictionaries by Key with a Lambda in Python

Sort a list of dictionaries ascending or descending by one of their keys using sorted() with a lambda as the key function — a beginner-friendly pattern.

sorting lambda dictionaries
Python
def get_students():
    return [
        {"name": "alice", "score": 85},
        {"name": "bob", "score": 92},
        {"name": "carol", "score": 78},
        {"name": "dave", "score": 92},
    ]

students = get_students()

sorted_by_score = sorted(students, key=lambda s: s["score"])
print("Sorted by score (ascending)…
13 0 Open
Functions & basics easy

How to Use Lambda Sorting Keys in Python

Learn to sort lists of dictionaries using lambda functions as key arguments in Python's sorted() method.

lambda sorting beginner
Python
# Demonstrate lambda as a sorting key function

students = [
    {"name": "Alice", "grade": 88},
    {"name": "Bob", "grade": 92},
    {"name": "Charlie", "grade": 75},
    {"name": "Diana", "grade": 95}
]

# Sort by grade (ascending) using a lambda key
sorted_by_grade = sorted(students, key=lambda student: student["g…
15 0 Open
Functions & basics easy

How to Use a Dispatch Table in Python (Map Strings to Functions)

Maps string command names to callable functions in a dictionary, then dispatches calls safely with error handling.

dispatch-table dictionary functions
Python
def add(a, b):
    return a + b


def subtract(a, b):
    return a - b


def multiply(a, b):
    return a * b


def divide(a, b):
    if b == 0:
        raise ValueError("Division by zero")
    return a / b


dispatch = {
    "add": add,
    "subtract": subtract,
    "multiply": multiply,
    "divide": divide,
}


def…
13 0 Open
Functions & basics easy

Sort a List of Dictionaries by Key in Python

Uses a lambda function with sorted() to order a list of dictionaries by a specified key, like price.

lambda sorting list
Python
def get_items():
    return [
        {"name": "apple", "price": 3},
        {"name": "banana", "price": 1},
        {"name": "cherry", "price": 2},
    ]

if __name__ == "__main__":
    items = get_items()
    sorted_items = sorted(items, key=lambda item: item["price"])
    for item in sorted_items:
        print(f"{…
12 0 Open
Errors & debugging easy

How to Catch KeyError with a Default Value in Python Dictionaries

Safely retrieve dictionary values while catching KeyError and handling None values by returning a default.

keyerror dictionary error-handling
Python
def get_value(data, key, default=None):
    """
    Safely get a value from a dictionary, returning a default if the key
    is missing or the value is None.
    """
    try:
        value = data[key]
        return value if value is not None else default
    except KeyError:
        return default


if __name__ == "_…
13 0 Open
Errors & debugging medium

How to Diff Two Dicts in Python for Config Drift

Recursively compare two dictionaries and report added, removed, and changed keys with their old and new values for debugging configuration drift.

dict diff config
Python
def diff_dicts(a, b, path=""):
    differences = []

    for key in a.keys() | b.keys():
        new_path = f"{path}.{key}" if path else key

        if key not in a:
            differences.append((new_path, "<missing>", b[key], "added"))
        elif key not in b:
            differences.append((new_path, a[key], "<…
12 0 Open
Errors & debugging medium

How to Log Errors with Structured Fields in Python

Logs error details as structured dictionary fields using Python's logging module with extra parameters.

logging errors structured
Python
import logging
import sys

def log_structured_error(operation: str, user_id: int, status_code: int, error_msg: str):
    """Log an error with structured fields using a dictionary."""
    logger = logging.getLogger("structured_logger")
    logger.setLevel(logging.ERROR)
    
    # Create console handler if not already …
14 0 Open
Errors & debugging easy

How to Serialize an Exception to a JSON-Safe Dict in Python

Convert any Python exception into a JSON-safe dictionary with type, message, and the last few traceback lines for logging.

exceptions json logging
Python
import json
import traceback
from typing import Any


def exception_to_dict(exc: Exception) -> dict[str, Any]:
    """Convert an exception into a JSON-safe dictionary."""
    return {
        "type": type(exc).__name__,
        "message": str(exc),
        "traceback": traceback.format_exc().strip().split("\n")[-3:],
…
15 0 Open
Errors & debugging easy

How to Use Optional Return in Python Instead of Raising Exceptions

A Python function returns None for missing dictionary keys instead of raising KeyError, enabling graceful lookup handling with type hints.

optional typing dict-get
Python
from typing import Optional


def find_user(users: dict, user_id: int) -> Optional[dict]:
    """
    Look up a user by ID. Returns the user dict if found,
    otherwise returns None instead of raising KeyError.
    """
    return users.get(user_id)


def main() -> None:
    users = {
        1: {"name": "Alice", "ema…
14 0 Open
Errors & debugging easy

Map Exception Type to HTTP Status Code in Python

Maps Python exception types to appropriate HTTP status codes using a dictionary lookup for consistent API error handling.

exceptions http-status error-handling
Python
EXCEPTION_STATUS_MAP = {
    ValueError: 400,
    KeyError: 400,
    TypeError: 400,
    PermissionError: 403,
    FileNotFoundError: 404,
    AttributeError: 404,
    TimeoutError: 408,
    NotImplementedError: 501,
    ConnectionError: 503,
}


def status_code_for(exception_type):
    try:
        return EXCEPTION_S…
13 0 Open
Errors & debugging easy

Python dict try-except KeyError EAFP vs LBYL

Compare EAFP (try-except) and LBYL (if-in-check) styles for safely accessing dictionary keys, with working examples in Python.

eafp lbyl dictionary
Python
def safe_get_lbyl(d, key):
    if key in d:
        return d[key]
    return "default-lbyl"

def safe_get_eafp(d, key):
    try:
        return d[key]
    except KeyError:
        return "default-eafp"

if __name__ == "__main__":
    data = {"name": "Alice", "age": 30}
    print("LBYL:", safe_get_lbyl(data, "missing")…
14 0 Open
Errors & debugging easy

Use pprint for Nested Structure Debug Output in Python

Pretty-print nested dictionaries and lists with pprint for readable, organized debug output.

pprint debugging nested-structure
Python
from pprint import pprint

def build_nested_structure():
    """Create a sample nested data structure for demonstration."""
    return {
        "project": "DataPipeline",
        "config": {
            "inputs": ["raw_1.json", "raw_2.json"],
            "processing": {
                "steps": ["clean", "transform",…
15 0 Open
Files & data easy

Build a File Index by Relative Path Hash Map in Python

Recursively walk a directory and map normalized relative paths to absolute file paths using a defaultdict hash map.

os.walk file-index defaultdict
Python
import os
from collections import defaultdict


def build_file_index(root_dir):
    index = defaultdict(list)

    for dirpath, dirnames, filenames in os.walk(root_dir):
        for filename in filenames:
            full_path = os.path.join(dirpath, filename)
            relative_path = os.path.relpath(full_path, roo…
19 0 Open
Files & data easy

Convert File Data to a Dictionary in Python

This function scans a directory and converts each file's metadata (name, size, extension) into a structured dictionary for easy access.

file-metadata pathlib directory
Python
from pathlib import Path

def convert_files_data(directory: str) -> dict:
    data = {}
    base = Path(directory)
    if not base.exists():
        return data
    for file in base.iterdir():
        if file.is_file():
            data[file.name] = {
                "size": file.stat().st_size,
                "exten…
15 0 Open
Files & data easy

Export List of Dicts to CSV in Python

Write a list of dictionaries (dataframe-like) to a CSV file with headers using the standard library csv module and verify by reading it back.

csv export dictwriter
Python
import csv

def export_to_csv(data, filename):
    """Export a list of dicts to a CSV file."""
    if not data:
        print("No data to export")
        return
    
    # Get column names from the keys of the first dict
    fieldnames = list(data[0].keys())
    
    with open(filename, 'w', newline='', encoding='utf…
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.