Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
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.
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 …
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.
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__":
…
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.
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…
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.
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…
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.
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)
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.
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…
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.
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",…
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
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- 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.