Reference library

Python Code Samples

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

74 matches
Files & data easy

Parse CSV with Custom Delimiter and Quote Character in Python

Reads a CSV string with a custom delimiter and quote character using the csv module, returning a list of rows.

csv parsing delimiter
Python
import csv
from io import StringIO

def parse_csv(data, delimiter='|', quotechar='"'):
    reader = csv.reader(StringIO(data), delimiter=delimiter, quotechar=quotechar)
    rows = [row for row in reader]
    return rows

if __name__ == "__main__":
    sample = 'Alice|"Smith, Jr."|25\nBob|"Johnson, Sr."|30'
    result …
13 0 Open
Files & data easy

Parse Fixed Width Data File by Column Slices in Python

Extract fields from fixed-width text by slicing each line at defined column offsets, with a dictionary describing the boundaries.

fixed-width string-slicing parsing
Python
from pathlib import Path


def parse_fixed_width(data: str, slices: dict[str, tuple[int, int]]) -> list[dict[str, str]]:
    lines = data.strip().splitlines()
    records = []
    for line in lines:
        record = {}
        for name, (start, end) in slices.items():
            record[name] = line[start:end].strip()…
13 0 Open
Files & data easy

Read a CSV File with csv.DictReader in Python

Read a CSV file as a list of dictionaries, using csv.DictReader to map each row to column names.

csv csv-dictreader file-reading
Python
import csv
from pathlib import Path

def read_csv_with_dictreader(file_path):
    data = []
    with open(file_path, mode='r', newline='', encoding='utf-8') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            data.append(row)
    return data

if __name__ == "__main__":
    # Cre…
10 0 Open
Files & data easy

Read an XML File with xml.etree.ElementTree in Python

Parse an XML file and print its root and child elements using the standard library's xml.etree.ElementTree module.

xml elementtree file-io
Python
import xml.etree.ElementTree as ET


def read_xml_file(file_path):
    """Read an XML file and print its structure."""
    tree = ET.parse(file_path)
    root = tree.getroot()
    print(f"Root element: {root.tag}")
    for child in root:
        print(f"Child element: {child.tag}, text: {child.text}")


if __name__ ==…
12 0 Open
Dictionaries & sets easy

How to Parse Data Into Dictionaries and Sets in Python

Parses raw student strings into a dictionary of lists and finds unique courses using a set.

dictionary set defaultdict
Python
from collections import defaultdict

def parse_students(raw_data):
    """Parse raw student strings into a dictionary of lists."""
    parsed = defaultdict(list)
    for entry in raw_data:
        name, _, course = entry.partition(":")
        parsed[course.strip()].append(name.strip())
    return dict(parsed)

def fi…
12 0 Open
Dictionaries & sets easy

How to Parse Query String to Dict with Duplicate Keys in Python

Convert a URL query string into a Python dictionary, merging duplicate keys into lists while keeping single values as scalars.

query-string dict url-parsing
Python
from urllib.parse import parse_qs


def parse_query_to_dict(query_string):
    parsed = parse_qs(query_string, keep_blank_values=True)
    return {key: values if len(values) > 1 else values[0] for key, values in parsed.items()}


if __name__ == "__main__":
    query = "name=John&name=Jane&age=30&city=&city=Paris&empty…
13 0 Open
Dictionaries & sets easy

How to convert string values to int or float in Python dicts

Recursively convert string values in nested dicts and lists to ints or floats when possible, leaving other strings untouched.

dict type-conversion recursion
Python
def coerce_str_values(data):
    """Recursively convert string values that look like ints or floats."""
    if isinstance(data, dict):
        return {key: coerce_str_values(val) for key, val in data.items()}
    elif isinstance(data, list):
        return [coerce_str_values(item) for item in data]
    elif isinstance…
12 0 Open
Dictionaries & sets easy

Parse Env Vars into Typed Dict in Python

Convert a list of environment variable names into a dictionary with automatically detected types (bool, int, float, or string), defaulting missing vars to None.

env-vars type-conversion dict
Python
import os
from typing import Any, Dict


def parse_env_vars(env_names: list[str], env: Dict[str, str] | None = None) -> Dict[str, Any]:
    """Parse a list of environment variable names into a typed dict.

    Each variable is parsed as:
    - bool: "true"/"false" (case-insensitive)
    - int: if it can be converted t…
13 0 Open
OOP & classes easy

Parse CSV Data with a Python Class

Encapsulate CSV file loading and column/row access methods in a reusable DataParser class for beginners.

oop csv parsing
Python
class DataParser:
    def __init__(self, file_path):
        self.file_path = file_path
        self.data = []

    def load_data(self):
        with open(self.file_path, 'r') as file:
            for line in file:
                row = line.strip().split(',')
                self.data.append(row)
        return self.…
12 0 Open
Comprehensions & generators easy

How to Parse CSV Rows as Generator Dicts in Python

Reads a CSV file and yields each row as a dictionary one at a time using a generator, so the file is processed lazily.

csv generator parsing
Python
import csv
from pathlib import Path

def csv_to_dicts(filepath):
    with open(filepath, mode="r", newline="", encoding="utf-8") as file:
        reader = csv.DictReader(file)
        for row in reader:
            yield row

if __name__ == "__main__":
    sample_csv = Path("sample_data.csv")
    sample_csv.write_text…
13 0 Open
Comprehensions & generators medium

How to stream parse JSON arrays in Python

This code demonstrates two generators: one that streams a JSON array as individual chunks, and another that incrementally parses those chunks into Python objects using json.JSONDecoder.

json generator streaming
Python
import json


def json_array_stream(items):
    """Generator that yields JSON-encoded values one at a time."""
    yield "["
    for i, item in enumerate(items):
        if i > 0:
            yield ","
        yield json.dumps(item)
    yield "]"


def parse_json_stream(stream):
    """Consumes a stream of JSON fragme…
14 0 Open
AI & LLM integration patterns easy

How to Parse Chat Completion JSON in Python

Parse a mock OpenAI chat completion JSON response into a clean dictionary with content, finish reason, and model.

json openai chat-completion
Python
import json

def parse_chat_response(raw: str) -> dict:
    data = json.loads(raw)
    choice = data["choices"][0]
    return {
        "content": choice["message"]["content"],
        "finish_reason": choice["finish_reason"],
        "model": data["model"],
    }

if __name__ == "__main__":
    mock_response = '''
  …
14 0 Open
AI & LLM integration patterns easy

How to Parse JSON from LLM Model Output Fence in Python

Extract and parse a JSON object from a language model's output that may be wrapped in triple-backtick fences with an optional language tag.

json llm parsing
Python
import json
import re

def parse_json_from_fence(text):
    """
    Extract JSON object from a model output that may be wrapped in
    triple-backtick fences with optional language tag.
    """
    # Match content inside
12 0 Open
AI & LLM integration patterns easy

How to Parse an LLM Response in Python

This code parses a JSON string from an LLM response, stripping code fences and handling common issues like whitespace, returning a Python dictionary.

llm json parsing
Python
import json
from typing import Any, Dict, List


def parse_llm_response(response: str) -> Dict[str, Any]:
    """Parse a JSON string from an LLM response, handling common edge cases."""
    # Remove code fences if present
    cleaned = response.strip()
    if cleaned.startswith("
13 0 Open
AI & LLM integration patterns medium

How to Repair Malformed JSON Braces Heuristically in Python

Heuristically fix malformed JSON by balancing braces and quotes, using a stack-based approach to add missing closing characters.

json repair heuristic
Python
import json
import re

def repair_json(text: str) -> str:
    """Heuristically repair malformed JSON by balancing braces and quotes."""
    # Trim whitespace and handle leading/trailing garbage
    text = text.strip()
    
    # Remove common non-JSON decorations
    text = re.sub(r'^(
13 0 Open
AI & LLM integration patterns easy

How to parse JSON in Python: A Beginner's Guide with Code Examples

This guide shows you how to parse JSON data in Python step by step, with practical code examples and expected outputs.

json parsing dictionary
Python
import json
from typing import Any, Dict, List, Optional


class DataHelper:
    """Beginner-friendly helper for common AI/LLM data tasks."""
    
    def __init__(self, data: Optional[Dict[str, Any]] = None):
        self.data = data or {}
    
    def to_prompt(self, template: str) -> str:
        """Format a prompt…
14 0 Open
AI & LLM integration patterns medium

Parse ReAct Logs into Thought Action Observation Steps in Python

Parse a ReAct agent's textual log into structured steps with thought, action, and observation using regex and named tuples.

react regex llm
Python
import re
from collections import namedtuple


ReActStep = namedtuple("ReActStep", ["thought", "action", "observation"])


def parse_react_log(log: str) -> list[ReActStep]:
    """Parse a ReAct log into structured thought/action/observation steps."""
    pattern = re.compile(
        r"Thought:\s*(?P<thought>.+?)\s*"
…
13 0 Open
Automation & scripting medium

Build a Website Accessibility Scanner Using Python

Scans a webpage for common accessibility issues like missing alt text, headings, labels, and landmarks using only Python.

accessibility a11y html
Python
import requests
from urllib.parse import urljoin
from html.parser import HTMLParser
import re

class AccessibilityParser(HTMLParser):
    def __init__(self):
        super().__init__()
        self.images_without_alt = []
        self.missing_headings = True
        self.has_main_tag = False
        self.label_for_inp…
40 0 Open
Automation & scripting medium

Convert DOCX to Text by Unzipping XML in Python

Extract plain text from a .docx file by unzipping the container and parsing word/document.xml with regex, using only Python's standard library.

docx zipfile xml
Python
import zipfile
import re
from pathlib import Path

def docx_to_text_unzip_xml(docx_path: str) -> str:
    """Extract plain text from a .docx file by unzipping and parsing document.xml."""
    docx_path = Path(docx_path)
    if not docx_path.exists():
        raise FileNotFoundError(f"File not found: {docx_path}")

   …
12 0 Open
Automation & scripting medium

Extract All Links from Any Website in Python

Scrape a webpage and extract all absolute HTTP/HTTPS links using requests and regex.

web-scraping links requests
Python
import requests
import re
from urllib.parse import urljoin

def extract_links(url):
    try:
        response = requests.get(url)
        response.raise_for_status()
        html = response.text
        # Find all href attributes in anchor tags
        pattern = r'href=["\'](.*?)["\']'
        raw_links = re.findall(p…
44 0 Open
Automation & scripting medium

Extract Every Open Graph and Social Media Meta Tag from Web Pages in Python

A Python script that fetches a webpage and extracts all Open Graph, Twitter Card, Facebook, and Article meta tags using the standard library HTML parser.

meta tags open graph twitter cards
Python
from html.parser import HTMLParser
import re
from urllib.request import urlopen
from urllib.parse import urlparse

class MetaExtractor(HTMLParser):
    def __init__(self):
        super().__init__()
        self.meta_tags = []
    
    def handle_starttag(self, tag, attrs):
        if tag == 'meta':
            attrs_…
34 0 Open
Automation & scripting medium

Generate Beautiful Project Documentation from Python Source Code Automatically

Automatically generate a markdown summary of function docstrings from any Python source file using the AST module.

ast automation documentation
Python
import ast
import inspect
from pathlib import Path

def extract_docstrings_from_file(filepath):
    """Parse a Python file and collect function docstrings."""
    source = Path(filepath).read_text()
    tree = ast.parse(source)

    docs = []
    for node in ast.walk(tree):
        if isinstance(node, (ast.FunctionDef…
34 0 Open
Automation & scripting medium

How to Generate a Dependency Graph for Python Projects

This script walks through a Python project directory, parses each .py file's imports, and prints a dependency graph showing which modules depend on which other modules.

ast dependency graph import parsing
Python
import os
import ast
from pathlib import Path
from collections import defaultdict

def get_imports(filepath):
    with open(filepath) as f:
        try:
            tree = ast.parse(f.read())
        except SyntaxError:
            return []
    imports = []
    for node in ast.walk(tree):
        if isinstance(node, …
39 0 Open
Automation & scripting easy

How to Import Users from CSV into LDAP-like Dicts in Python

Reads a CSV of user records and converts each row into an LDAP-style dictionary with standard attributes using Python's csv module.

csv ldap import
Python
import csv
import io
from pathlib import Path


def mock_ldap_import(csv_path):
    """
    Reads a CSV file with user data and returns a list of LDAP-like user dicts.
    Adds standard LDAP attributes that would come from directory schema.
    """
    with open(csv_path, newline="", encoding="utf-8") as csvfile:
    …
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.