Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
Find Most Frequent Character in a String in Python
Count character frequencies in a Python string using a dictionary and return the character that appears most often with a max() key function.
def most_frequent_char(s: str) -> str:
if not s:
return ""
char_count = {}
for ch in s:
char_count[ch] = char_count.get(ch, 0) + 1
max_char = max(char_count, key=char_count.get)
return max_char
if __name__ == "__main__":
text = "programming"
result = most_frequent…
How to Format Strings with Named Placeholders in Python
Format a template string using named placeholders with the str.format() method and a dictionary.
def format_named(template, data):
"""Format a template string using named placeholders."""
return template.format(**data)
if __name__ == "__main__":
template = "Hello {name}, you are {age} years old and live in {city}."
data = {"name": "Alice", "age": 30, "city": "London"}
result = format_named(t…
How to Group Data by Category in Python
Group a list of (category, value) tuples into a dictionary of lists using the setdefault method.
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…
How to Validate Text Input in Python: A Simple Text Processor
A Python function that validates a text string by trimming whitespace, then returns a dictionary with character, word, and sentence counts.
def validate_text(text: str) -> dict:
"""Analyze a text string and return basic validation statistics."""
stripped = text.strip()
if not stripped:
return {
"valid": False,
"reason": "Text is empty or only whitespace",
"characters": 0,
"words": 0,
…
How to parse key=value pairs in Python
Parse a single line of key=value pairs separated by a delimiter into a Python dictionary.
def parse_key_value_pairs(line: str, delimiter: str = "&") -> dict:
"""Parse a single line of key=value pairs into a dictionary."""
pairs = {}
for token in line.split(delimiter):
if not token.strip():
continue
key, _, value = token.partition("=")
pairs[key.strip()] = val…
How to Build a Frequency Map from a List in Python
This code builds a dictionary that maps each unique element in a list to its count using the Counter class from the collections module.
from collections import Counter
def build_frequency_map(values):
"""Return a dictionary mapping each unique value to its frequency."""
return dict(Counter(values))
if __name__ == "__main__":
data = ["apple", "banana", "apple", "cherry", "banana", "apple"]
freq_map = build_frequency_map(data)
prin…
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.
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:…
How to Load a .env File Manually in Python
Parse a .env-style key-value file into a Python dictionary using only the standard library, with comment and quoted-value handling.
import re
from pathlib import Path
def load_dotenv_file(filepath: str) -> dict[str, str]:
"""Parse a .env-style file into a dictionary."""
env = {}
path = Path(filepath)
if not path.exists():
raise FileNotFoundError(f"Environment file not found: {filepath}")
for line in path.read_text()…
How to Use a Dispatch Table in Python (Map Strings to Functions)
Maps string command names to callable functions in a dictionary, then dispatches calls safely with error handling.
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
raise ValueError("Division by zero")
return a / b
dispatch = {
"add": add,
"subtract": subtract,
"multiply": multiply,
"divide": divide,
}
def…
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.
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__ == "_…
How to Log Errors with Structured Fields in Python
Logs error details as structured dictionary fields using Python's logging module with extra parameters.
import logging
import sys
def log_structured_error(operation: str, user_id: int, status_code: int, error_msg: str):
"""Log an error with structured fields using a dictionary."""
logger = logging.getLogger("structured_logger")
logger.setLevel(logging.ERROR)
# Create console handler if not already …
How to Serialize an Exception to a JSON-Safe Dict in Python
Convert any Python exception into a JSON-safe dictionary with type, message, and the last few traceback lines for logging.
import json
import traceback
from typing import Any
def exception_to_dict(exc: Exception) -> dict[str, Any]:
"""Convert an exception into a JSON-safe dictionary."""
return {
"type": type(exc).__name__,
"message": str(exc),
"traceback": traceback.format_exc().strip().split("\n")[-3:],
…
How to Use Optional Return in Python Instead of Raising Exceptions
A Python function returns None for missing dictionary keys instead of raising KeyError, enabling graceful lookup handling with type hints.
from typing import Optional
def find_user(users: dict, user_id: int) -> Optional[dict]:
"""
Look up a user by ID. Returns the user dict if found,
otherwise returns None instead of raising KeyError.
"""
return users.get(user_id)
def main() -> None:
users = {
1: {"name": "Alice", "ema…
Map Exception Type to HTTP Status Code in Python
Maps Python exception types to appropriate HTTP status codes using a dictionary lookup for consistent API error handling.
EXCEPTION_STATUS_MAP = {
ValueError: 400,
KeyError: 400,
TypeError: 400,
PermissionError: 403,
FileNotFoundError: 404,
AttributeError: 404,
TimeoutError: 408,
NotImplementedError: 501,
ConnectionError: 503,
}
def status_code_for(exception_type):
try:
return EXCEPTION_S…
Python dict try-except KeyError EAFP vs LBYL
Compare EAFP (try-except) and LBYL (if-in-check) styles for safely accessing dictionary keys, with working examples in Python.
def safe_get_lbyl(d, key):
if key in d:
return d[key]
return "default-lbyl"
def safe_get_eafp(d, key):
try:
return d[key]
except KeyError:
return "default-eafp"
if __name__ == "__main__":
data = {"name": "Alice", "age": 30}
print("LBYL:", safe_get_lbyl(data, "missing")…
Convert File Data to a Dictionary in Python
This function scans a directory and converts each file's metadata (name, size, extension) into a structured dictionary for easy access.
from pathlib import Path
def convert_files_data(directory: str) -> dict:
data = {}
base = Path(directory)
if not base.exists():
return data
for file in base.iterdir():
if file.is_file():
data[file.name] = {
"size": file.stat().st_size,
"exten…
How to Group Files by Extension in Python
Group file names by their file extension using a dictionary and pathlib, producing a simple clear mapping for beginners.
from pathlib import Path
def group_data_by_extension(files: list[Path]) -> dict[str, list[str]]:
"""Group file names by their extension."""
grouped: dict[str, list[str]] = {}
for file in files:
ext = file.suffix.lower()
grouped.setdefault(ext, []).append(file.name)
return grouped
if…
How to Parse XML Attributes into a Flat Dictionary in Python
Parses XML elements and attributes using ElementTree, building a flat dictionary keyed by element attributes.
import xml.etree.ElementTree as ET
xml_data = """<root>
<book id="1" category="fiction" price="9.99">
<title>The Catcher</title>
</book>
<book id="2" category="nonfiction" price="12.50">
<title>Deep Learning</title>
</book>
</root>"""
def parse_xml_attributes(xml_string):
root = E…
How to Read a JSON File into a Dictionary in Python
Load a JSON file into a Python dictionary using the json.load() function with proper file handling and UTF-8 encoding.
import json
from pathlib import Path
def read_json_file(filepath: str) -> dict:
"""Read a JSON file and return its contents as a dictionary."""
path = Path(filepath)
with path.open("r", encoding="utf-8") as f:
data = json.load(f)
return data
if __name__ == "__main__":
# Create a sample JS…
How to Split Files by Extension in Python
Group files in a folder by their file extension into a dictionary using pathlib.
from pathlib import Path
def split_files_by_extension(folder_path):
folder = Path(folder_path)
files_by_ext = {}
for file_path in folder.iterdir():
if file_path.is_file():
ext = file_path.suffix.lower() or "no_extension"
files_by_ext.setdefault(ext, []).append(file_path.na…
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:
…
How to Write a Dict to a Pretty JSON File with Indent in Python
Serializes a Python dictionary to a readable JSON file using json.dump with indentation and sorted keys, then prints the file contents to stdout.
import json
from pathlib import Path
data = {
"name": "Python",
"version": 3.12,
"features": ["simple", "readable", "powerful"],
"nested": {"creator": "Guido van Rossum", "year": 1991}
}
output_path = Path("output.json")
with output_path.open("w", encoding="utf-8") as f:
json.dump(data, f, inden…
Parse Fixed Width Data File by Column Slices in Python
Extract fields from fixed-width text by slicing each line at defined column offsets, with a dictionary describing the boundaries.
from pathlib import Path
def parse_fixed_width(data: str, slices: dict[str, tuple[int, int]]) -> list[dict[str, str]]:
lines = data.strip().splitlines()
records = []
for line in lines:
record = {}
for name, (start, end) in slices.items():
record[name] = line[start:end].strip()…
Read Parquet-Like Columnar CSV Chunks in Python
A Python generator that reads a CSV file column-by-column, yielding dictionary chunks where each key points to a list of values—mirroring how Parquet stores data columnar.
```python
import csv
from pathlib import Path
from typing import Iterator, List
def read_parquet_like_columnar(csv_path: str, column_names: List[str], chunk_size: int = 2) -> Iterator[dict]:
"""Read CSV data in columnar chunks, similar to how parquet stores columns."""
csv_file = Path(csv_path)
with csv_f…
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.