Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Merge Dicts from Two JSON Files Like a Pro
This helper reads two JSON files that contain dicts, merges them with the second file overriding duplicate keys, and saves the result to a new file.
import json
from pathlib import Path
def merge_json_files(file1: str, file2: str, output: str = "merged.json") -> dict:
"""Merge two JSON files containing dicts, with file2 overriding file1."""
data1 = json.loads(Path(file1).read_text())
data2 = json.loads(Path(file2).read_text())
merged = {**data1,…
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.
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…
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.
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__":…
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.
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:
…
Compare Two Dictionaries in Python
Compare two dictionaries by finding common keys, unique keys, and value differences using Python's set operations.
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…
Convert Lists and Dictionaries to Sets in Python
Convert lists of pairs into dictionaries and lists or dictionaries into sets using simple helper functions.
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…
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 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.
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…
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.
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…
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.
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…
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.
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…
Validate dictionary data with sets in Python
Validate a dictionary against required keys and allowed value sets, returning a list of validation errors.
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(…
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.
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…
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.
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]
…
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 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…
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.
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
…
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.
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…
How to Create a Data Formatter Class in Python
A beginner-friendly helper class to format lists, dictionaries, and stored records into readable strings.
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, …
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.
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…
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.
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…
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.
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…
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.
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…
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.
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 …
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.
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 {
…
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.