Reference library

Python Code Samples

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

9 matches
Strings & text easy

How to Merge Strings in Python

Merge multiple strings or a list of text lines into one string with a custom separator

strings join merging
Python
def merge_strings(*parts, separator=" "):
    """Merge multiple string parts into one string with a separator."""
    return separator.join(parts)


def merge_text_lines(lines, separator="\n"):
    """Merge a list of text lines into a single string."""
    return separator.join(lines)


if __name__ == "__main__":
    …
15 0 Open
Files & data easy

How to Merge Environment-Specific Config JSON in Python

Loads a base JSON config and overlays environment-specific overrides, merging the two dictionaries into one final config.

json config pathlib
Python
import json
import pathlib


def load_config(base_path: pathlib.Path, env: str) -> dict:
    base_config = json.loads(base_path.read_text())
    env_path = base_path.with_name(f"config.{env}.json")
    if env_path.exists():
        env_config = json.loads(env_path.read_text())
        return {**base_config, **env_conf…
14 0 Open
Files & data easy

Merge Multiple PDF Files into One Document in Python

Combines multiple PDF files into a single PDF document using the PyPDF2 library's PdfMerger class.

pdf pypdf2 file-merging
Python
import PyPDF2

def merge_pdfs(input_paths, output_path):
    merger = PyPDF2.PdfMerger()
    for path in input_paths:
        merger.append(path)
    merger.write(output_path)
    merger.close()
    print(f"Merged {len(input_paths)} PDFs into '{output_path}'.")

if __name__ == "__main__":
    files = ["file1.pdf", "fi…
43 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
OOP & classes easy

How to merge dictionaries by a key in Python with a class

This code defines a DataMerger class that collects dictionary records and merges them by a specified key, combining fields from multiple records with the same key.

classes dictionaries merging
Python
class DataMerger:
    def __init__(self):
        self.records = []

    def add_record(self, record):
        if isinstance(record, dict):
            self.records.append(record)
        else:
            raise TypeError("Record must be a dictionary")

    def merge_by_key(self, key):
        merged = {}
        for …
13 0 Open
Comprehensions & generators easy

Merge Data with Comprehension and Generator in Python

Merge user and order data using a dictionary comprehension for lookups and a generator expression to filter and transform orders.

dictionary-comprehension generator-expression data-merging
Python
def merge_data(users, orders):
    """
    Merge user and order data using a dictionary comprehension
    and a generator expression for filtering.
    """
    # Build a lookup: user_id -> user name
    user_map = {user["id"]: user["name"] for user in users}

    # Generator: yield orders with user names attached
    …
14 0 Open
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
Big data & Spark easy

Compaction Small Files Mock in Python

Simulates a small-files compaction job by creating small mock files and merging them into a single output file using Python's standard library.

compaction file-io mock
Python
from pathlib import Path
import tempfile
import os


def create_small_files(directory: Path, file_count: int = 5, lines_per_file: int = 3):
    """Create several small mock files with sample content."""
    directory.mkdir(exist_ok=True)
    for i in range(file_count):
        file_path = directory / f"part-{i:04d}.tx…
17 0 Open
Big data & Spark easy

Hudi Upsert Mock Copy on Write in Python

Simulates Apache Hudi's Copy-on-Write upsert behavior by merging update records into a deep copy of base records, replacing matches or appending new ones.

hudi upsert copy-on-write
Python
import copy
from typing import Dict, List, Any

def upsert_copy_on_write(base_records: List[Dict[str, Any]], updates: List[Dict[str, Any]], key_field: str = "id") -> List[Dict[str, Any]]:
    """Simulate Hudi Copy-on-Write upsert: merge updates into a copy of base records."""
    result = copy.deepcopy(base_records)
 …
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.