Reference library

Python Code Samples

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

118 matches
Files & data easy

How to Read and Write Files in Python (JSON + Text)

A beginner-friendly helper module to read and write JSON and text files using Python's pathlib and json standard library modules.

json file-io pathlib
Python
import json
from pathlib import Path


def load_json_file(filepath):
    """Load data from a JSON file and return as dict/list."""
    path = Path(filepath)
    with path.open("r", encoding="utf-8") as f:
        return json.load(f)


def save_json_file(filepath, data):
    """Save data to a JSON file."""
    path = P…
14 0 Open
Files & data easy

How to Read and Write Text Files in Python

This code provides simple helper functions to save and load text files using Python's standard pathlib library.

file-io pathlib text-files
Python
from pathlib import Path


def save_text_data(filename: str, content: str) -> None:
    file_path = Path(filename)
    file_path.write_text(content, encoding="utf-8")


def load_text_data(filename: str) -> str:
    file_path = Path(filename)
    return file_path.read_text(encoding="utf-8")


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

How to Validate a JSON File in Python

A beginner-friendly Python helper that reads a JSON file, catches common errors, and returns a status dictionary.

json validation file-handling
Python
import json
from pathlib import Path

def get_valid_json_data(file_path: str) -> dict:
    file = Path(file_path)
    if not file.exists():
        return {"status": "error", "message": f"File not found: {file_path}"}
    
    try:
        data = json.loads(file.read_text())
    except json.JSONDecodeError as e:
     …
12 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…
18 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

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 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
Dictionaries & sets easy

How to Check Data Type and Inspect Dictionaries and Sets in Python

Inspect dictionaries and sets by printing their contents, types, and sizes using a small helper function.

dictionaries sets isinstance
Python
def check_data(data):
    """Helper to inspect dictionaries and sets."""
    if isinstance(data, dict):
        print(f"Dictionary with {len(data)} keys")
        for key, value in data.items():
            print(f"  {key}: {value} ({type(value).__name__})")
    elif isinstance(data, set):
        print(f"Set with {le…
13 0 Open
Dictionaries & sets easy

How to Group Data by Category in Python with a Split Data Helper

This code groups a list of (category, item) pairs into a dictionary where each key is a category and each value is a list of items belonging to that category.

dictionary grouping iterable
Python
def split_data(categories):
    """
    Group data items into buckets based on a key function.
    Returns a dict where keys are bucket names and values are lists of items.
    """
    buckets = {}
    for category, item in categories:
        if category not in buckets:
            buckets[category] = []
        buck…
14 0 Open
Dictionaries & sets easy

How to Set Nested Dict Value Creating Missing Keys in Python

Set a value deep inside a nested dictionary, automatically creating any missing intermediate dicts along the path.

dictionary nested mutation
Python
def set_nested_value(d, keys, value):
    """
    Set a value in a nested dict, creating missing intermediate keys.
    
    Args:
        d: The dict to modify
        keys: Iterable of keys forming the path (e.g., ['a', 'b', 'c'])
        value: The value to set at the final key
    """
    current = d
    for key i…
13 0 Open
Dictionaries & sets easy

Validate dictionary data with sets in Python

Validate a dictionary against required keys and allowed value sets, returning a list of validation errors.

dictionaries sets validation
Python
def validate_data(data, required_keys, allowed_values=None):
    """
    Validate a dictionary against required keys and optional allowed value sets.
    Returns a list of validation errors (empty list if valid).
    """
    errors = []
    
    # Check for missing required keys
    missing = set(required_keys) - set(…
14 0 Open
OOP & classes easy

Design a Data Helper Class in Python

Create a simple Object-Oriented data helper with DataPoint and Dataset classes that store, describe, and summarize coordinate points.

oop classes data-helper
Python
class DataPoint:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.label = None

    def describe(self):
        """Return a human-readable description of the data point."""
        base = f"DataPoint(x={self.x}, y={self.y})"
        return f"{base}, label='{self.label}'" if self.label e…
15 0 Open
OOP & classes easy

Filtering data with a Python class helper

A beginner-friendly DataFilter class that filters lists of dictionaries by exact match, greater-than, and substring conditions.

filter oop class
Python
class DataFilter:
    """A beginner-friendly helper to filter lists of dictionaries."""
    
    def __init__(self, data):
        self.data = data
    
    def filter_by(self, key, value):
        """Return items where data[key] == value."""
        return [item for item in self.data if item.get(key) == value]
    
 …
14 0 Open
OOP & classes easy

Group Data Helper Class in Python

A simple Python class that stores items under named groups, retrieves groups, items, and counts, and formats them as a readable summary.

class grouping helper
Python
class GroupData:
    """A simple helper class to store and group data for beginners."""

    def __init__(self):
        self.items = []

    def add(self, item, group):
        """Add an item under a given group name."""
        self.items.append({"item": item, "group": group})

    def get_groups(self):
        """R…
14 0 Open
OOP & classes easy

How to Build a Data Helper Class in Python with OOP

Create a beginner-friendly Python class that loads CSV data, filters records by field, and counts entries using object-oriented programming.

oop csv data
Python
class DataHelper:
    """A beginner-friendly OOP helper for handling simple datasets."""
    
    def __init__(self, filename):
        self.filename = filename
        self.data = self._load_data()
    
    def _load_data(self):
        """Load data from a CSV file into a list of dictionaries."""
        import csv
 …
12 0 Open
OOP & classes easy

How to Convert Data Types in Python with a Helper Class

This code defines a beginner-friendly OOP helper class for common data conversions like string to list, list to dict, JSON string, and CSV row, with an advanced subclass for numeric casting.

oop classes data-conversion
Python
class DataConverter:
    """A beginner-friendly helper class for common data conversions."""
    
    def __init__(self, data):
        self.data = data
    
    def to_list(self):
        """Convert string data (comma-separated) to a list."""
        if isinstance(self.data, str):
            return [item.strip() for…
14 0 Open
OOP & classes easy

How to Create a Data Formatter Class in Python

A beginner-friendly helper class to format lists, dictionaries, and stored records into readable strings.

oop class formatting
Python
class DataFormatter:
    """Helper class for beginners to format common data types."""
    
    def __init__(self, name="data"):
        self.name = name
        self.records = []
    
    def add_record(self, key, value):
        """Add a key-value record to the formatter."""
        self.records.append({"key": key, …
12 0 Open
OOP & classes easy

How to Create a Data Helper Class in Python with OOP

A complete OOP example with User, Post, and Blog classes that manage data relationships and provide clear helper methods.

oop classes data-modeling
Python
class User:
    def __init__(self, name, email):
        self.name = name
        self.email = email
        self.posts = []

    def create_post(self, title, content):
        post = Post(title, content, self)
        self.posts.append(post)
        return post

    def get_post_count(self):
        return len(self.p…
12 0 Open
OOP & classes easy

How to Sort Data in Python with a Class Helper

This beginner-friendly class wraps the built-in sorted() function to sort numbers, strings ignoring case, and dictionaries by a specified key.

oop sorting sorted
Python
class DataSorter:
    def __init__(self, data):
        self.data = data

    def sort_numbers(self, reverse=False):
        return sorted(self.data, reverse=reverse)

    def sort_strings_ignore_case(self, reverse=False):
        return sorted(self.data, key=str.lower, reverse=reverse)

    def sort_dicts_by_key(self…
14 0 Open
OOP & classes easy

How to Use StrEnum with auto() in Python

Define string-valued enum members automatically by using StrEnum with the auto() helper, making each member's value its own uppercase name.

enum strenum auto
Python
from enum import StrEnum, auto

class Color(StrEnum):
    RED = auto()
    GREEN = auto()
    BLUE = auto()

class Language(StrEnum):
    PYTHON = auto()
    JAVASCRIPT = auto()
    RUST = auto()

print(list(Color))
print(list(Language))

print(Color.RED == "RED")
print(Language.PYTHON == "PYTHON")

print(f"Color: {Co…
13 0 Open
Comprehensions & generators easy

How to Filter Data with Predicates in Python

This helper filters a list with a predicate using a list comprehension, plus a lazy generator version that yields matches one by one.

filtering comprehensions generators
Python
def filter_data(data, predicate):
    """Return a list containing only items that pass the predicate."""
    return [item for item in data if predicate(item)]


def filter_data_lazy(data, predicate):
    """Generator version: yields items that pass the predicate one by one."""
    for item in data:
        if predicat…
16 0 Open
Comprehensions & generators easy

How to Group Data in Python with defaultdict and Comprehensions

Group a list of items by a computed key using a defaultdict-based generator helper and an alternative dictionary comprehension approach.

grouping defaultdict comprehensions
Python
from collections import defaultdict

def group_by(data, key_func):
    """Group items in data by the value returned by key_func."""
    result = defaultdict(list)
    for item in data:
        result[key_func(item)].append(item)
    return dict(result)

def group_by_comprehension(data, key_func):
    """Same grouping …
15 0 Open
Comprehensions & generators easy

How to Use Comprehensions and Generators to Check Data in Python

A beginner-friendly helper that filters numeric values, computes squares and cubes with comprehensions and a generator, and returns a summary dictionary.

comprehensions generators data-checking
Python
def check_data(iterable):
    """Return a summary of numeric data using comprehensions and a generator."""
    values = [item for item in iterable if isinstance(item, (int, float))]
    squares = [x ** 2 for x in values if x > 0]
    cubes = (x ** 3 for x in values if x > 0)
    cube_list = list(cubes)
    return {
  …
13 0 Open
Comprehensions & generators easy

How to Use List Comprehensions and Generators to Format Data in Python

A beginner-friendly helper that formats dictionaries into strings using a list comprehension and generates squared numbers lazily with a generator.

list comprehension generators formatting
Python
def format_data(items):
    """Format a list of dictionaries into readable strings."""
    formatted = [
        f"{item.get('name', 'Unknown')}: {item.get('value', 0)} units"
        for item in items
        if item.get('value', 0) > 0
    ]
    return formatted if formatted else ["No positive values found"]


def g…
13 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.