Reference library

Python Code Samples

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

7 matches
Files & data easy

How to Parse JSON, TXT, and CSV Files in Python

This code provides simple functions to read and parse JSON, text, and CSV files using Python's standard library, returning native data structures.

json csv file parsing
Python
import json
from pathlib import Path

def parse_json_file(filepath):
    """Read and parse a JSON file, returning its contents."""
    path = Path(filepath)
    with path.open('r', encoding='utf-8') as f:
        return json.load(f)

def parse_txt_lines(filepath):
    """Read a text file and return non-empty stripped …
14 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 Use Dictionaries and Sets in Python for Beginners

Demonstrates Python dictionary operations and set operations with examples, including access, modification, defaults, and set algebra.

dictionary set beginner
Python
def demonstrate_collections():
    # Dictionary basics
    student = {
        "name": "Alice",
        "age": 20,
        "courses": ["Math", "Physics"]
    }
    print("Dictionary:", student)

    # Access and modify
    student["age"] = 21
    student["grade"] = "A"
    print("Modified:", student)

    # Get with d…
11 0 Open
Dictionaries & sets easy

How to Use Dictionaries and Sets in Python for Beginners

Introduces Python dictionaries and sets with practical examples including creating, modifying, and performing set operations, plus a word-frequency counter.

dictionaries sets data structures
Python
def demonstrate_dict_sets():
    # Create a dictionary with basic info
    person = {
        "name": "Alice",
        "age": 30,
        "city": "New York"
    }
    print("Dictionary:", person)

    # Access and modify dictionary values
    person["age"] = 31
    person["email"] = "alice@example.com"
    print("Afte…
15 0 Open
Algorithms & data structures easy

How to Heapify a List into a Min Heap with heapq in Python

Convert any list into a valid min heap in-place using Python's heapq.heapify(), then pop the smallest element to verify heap order.

heapq min heap heapify
Python
import heapq

data = [5, 3, 8, 1, 9, 2, 7, 4, 6]
print("Original list:", data)

heapq.heapify(data)
print("Min heap:", data)

popped = heapq.heappop(data)
print("Smallest element popped:", popped)
print("Heap after pop:", data)
14 0 Open
Cloud + Python easy

How to Convert Python Dict to JSON and Back

Convert Python dictionaries to JSON text and back with a simple helper that serializes and deserializes data structures.

json dict serialization
Python
import json
from datetime import datetime, timezone


def convert_data(data, source_format=None, target_format="json"):
    """
    Convert Python data structures to txt/json and back.
    For beginners: shows how to serialize/deserialize.
    """
    if source_format == "json" and target_format == "dict":
        ret…
13 0 Open
Testing & modern typing easy

How to Use TypedDict and Dataclasses in Python

Create typed data structures with TypedDict and dataclasses, then use them as helper functions for describing objects in a type-safe way.

typing typdict dataclass
Python
from typing import TypedDict, NotRequired, Optional
from dataclasses import dataclass


class User(TypedDict):
    name: str
    age: NotRequired[int]
    email: Optional[str]


@dataclass
class Product:
    id: int
    title: str
    price: float = 0.0


def describe_user(user: User) -> str:
    age = user.get("age",…
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.