Reference library

Python Code Samples

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

92 matches
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
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 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

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 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

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
Files & data easy

How to List File Information in a Directory with Python

A helper that walks a directory and returns each file's name, size, and extension as a list of dictionaries.

pathlib filesystem file-metadata
Python
from pathlib import Path


def get_files_data(directory: str) -> list[dict]:
    """Return basic info about all files in a directory."""
    files = []
    for path in Path(directory).iterdir():
        if path.is_file():
            files.append({
                "name": path.name,
                "size": path.stat()…
12 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

How to Read a TSV File in Python with csv.DictReader

Read a tab-separated (TSV) file into dictionaries using the csv module's DictReader with a tab delimiter.

csv tsv file-io
Python
import csv
from pathlib import Path

data_file = Path("data.tsv")

# Sample TSV content (tab-separated)
sample = """name\tage\tcity
Alice\t30\tNew York
Bob\t25\tLos Angeles
Carol\t35\tChicago
"""
data_file.write_text(sample)

with data_file.open("r", newline="", encoding="utf-8") as f:
    reader = csv.DictReader(f, d…
14 0 Open
Files & data easy

How to Sort Files by Name and Size in Python

Sort a list of file dictionaries by name then size using Python's sorted() with a lambda key.

sorting files lambda
Python
from pathlib import Path

def sort_files_data(files):
    """Sort a list of file dictionaries by name, then by size."""
    return sorted(files, key=lambda f: (f["name"], f["size"]))

if __name__ == "__main__":
    files_data = [
        {"name": "report.pdf", "size": 2048},
        {"name": "data.csv", "size": 1024},…
13 0 Open
Files & data easy

Read SQLite database with sqlite3 module in Python

Connect to a SQLite database and query rows with the standard library sqlite3 module, returning results as dictionaries.

sqlite database stdlib
Python
import sqlite3
from pathlib import Path

# Create an in-memory database and a sample table
connection = sqlite3.connect(":memory:")
cursor = connection.cursor()

cursor.execute("""
CREATE TABLE employees (
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    department TEXT NOT NULL,
    salary REAL
)
""")

# Inser…
17 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

Write CSV file with csv DictWriter in Python

Write a list of dictionaries to a CSV file using Python's csv.DictWriter, including a header row.

csv file-writing dictwriter
Python
import csv
from pathlib import Path

fieldnames = ["name", "city", "age"]
rows = [
    {"name": "Alice", "city": "New York", "age": 30},
    {"name": "Bob", "city": "Los Angeles", "age": 25},
    {"name": "Charlie", "city": "Chicago", "age": 35},
]

path = Path("people.csv")
with path.open("w", newline="") as csvfile:…
16 0 Open
Dictionaries & sets easy

Build an OrderedDict insertion order demo in Python 3

Demonstrate how OrderedDict preserves insertion order, how updates keep position, and how re-insertion moves keys to the end.

ordereddict dictionaries insertion-order
Python
from collections import OrderedDict

def demo_ordered_dict():
    # Create an OrderedDict and insert items in a specific order
    ordered = OrderedDict()
    ordered['banana'] = 3
    ordered['apple'] = 2
    ordered['cherry'] = 5
    ordered['date'] = 1

    print("Insertion order preserved:")
    for key, value in …
13 0 Open
Dictionaries & sets easy

Compare Two Dictionaries in Python

Compare two dictionaries by finding common keys, unique keys, and value differences using Python's set operations.

dictionary set operations comparison
Python
def compare_data(dict1, dict2):
    """Compare two dictionaries and summarize similarities/differences."""
    keys1 = set(dict1.keys())
    keys2 = set(dict2.keys())
    
    common_keys = keys1 & keys2
    only_in_first = keys1 - keys2
    only_in_second = keys2 - keys1
    
    print(f"Common keys ({len(common_keys…
17 0 Open
Dictionaries & sets easy

Convert Lists and Dictionaries to Sets in Python

Convert lists of pairs into dictionaries and lists or dictionaries into sets using simple helper functions.

dict set conversion
Python
def convert_to_dict(data):
    """Convert list of tuples or lists into a dictionary."""
    return dict(data)


def convert_to_set(data):
    """Convert list or dictionary into a set of its keys/values."""
    if isinstance(data, dict):
        return set(data.keys())
    return set(data)


def convert_collection(data…
14 0 Open
Dictionaries & sets easy

Count Words in Python with Dictionaries and Sets

Text analysis example that counts total words, finds unique words with a set, and tallies character frequencies with a dictionary.

dictionaries sets text-processing
Python
def analyze_text(text: str) -> dict:
    """Count words, find unique words, and show common characters."""
    words = text.lower().split()
    word_count = len(words)
    unique_words = set(words)
    char_counts = {}
    
    for word in words:
        for char in word:
            if char.isalpha():
               …
13 0 Open
Dictionaries & sets easy

Filter Dictionary Keys by Prefix in Python

Use a dict comprehension to build a new dictionary containing only keys that start with a given prefix.

dict-comprehension filtering dictionaries
Python
def filter_dict_keys(data, prefix="temp_"):
    """
    Filter a dictionary by keeping only keys that start with a given prefix.
    Uses a dict comprehension to build a new dictionary.
    """
    if not isinstance(data, dict):
        raise ValueError("data must be a dictionary")
    return {key: value for key, valu…
13 0 Open
Dictionaries & sets easy

Group Data by Key in Python with Dictionaries and Sets

Group items into a dictionary of sets using a key function, a beginner-friendly pattern for organizing data by categories.

grouping dictionaries sets
Python
def group_data(items, key_func):
    """Group items into a dictionary of sets based on a key function."""
    grouped = {}
    for item in items:
        key = key_func(item)
        if key not in grouped:
            grouped[key] = set()
        grouped[key].add(item)
    return grouped


if __name__ == "__main__":
 …
15 0 Open
Dictionaries & sets easy

How to Aggregate Order Data with Sets and Dictionaries in Python

Combine sets and dictionaries to find unique products and total quantities from a list of orders in Python.

sets dictionaries data aggregation
Python
def find_unique_products(orders):
    """Return set of all products ordered across multiple orders."""
    all_products = set()
    for order in orders:
        all_products.update(order.get("items", []))
    return all_products


def product_summary(orders):
    """Build a dictionary mapping each product to its total…
13 0 Open
Dictionaries & sets easy

How to Build a Gradebook with Python Dictionaries and Sets

Create a gradebook dictionary from student names and grades, find top students with a set comprehension, and add extra credit with a dict comprehension.

dictionaries sets comprehensions
Python
def build_gradebook(students, grades):
    """Create a dictionary mapping student names to their grades."""
    return dict(zip(students, grades))


def find_top_students(gradebook, passing_grade=60):
    """Return a set of students with grades at or above the passing grade."""
    return {name for name, grade in grad…
12 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.