Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
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…
Check Invertible Mapping for Duplicate Values in Python
Detect duplicate values among (key, value) pairs to ensure the mapping is invertible, using a dictionary for O(1) lookups.
def invertible_after_dedup(pairs):
"""
Check whether a set of (key, value) pairs is invertible,
i.e., no duplicate values exist for different keys.
"""
seen = {}
for key, value in pairs:
if value in seen and seen[value] != key:
return False, f"Duplicate value '{value}' for k…
How to Index a List of Records by Unique ID in Python
Build a dictionary that maps each record's unique id to the record itself from a list of dictionaries.
from typing import List, Dict, Any
def index_by_id(records: List[Dict[str, Any]], id_field: str = "id") -> Dict[Any, Dict[str, Any]]:
"""Build a dictionary mapping each record's unique id to the record itself."""
return {record[id_field]: record for record in records}
if __name__ == "__main__":
sample_re…
How to Invert a Dictionary in Python Safely
Swap dictionary keys and values while detecting duplicate values to prevent silent data loss.
def invert_dict_safely(d):
inverted = {}
for key, value in d.items():
if value not in inverted:
inverted[value] = key
else:
raise ValueError(f"Duplicate value '{value}' would cause data loss")
return inverted
if __name__ == "__main__":
sample = {"a": 1, "b": 2,…
How to Use ChainMap for Layered Config Lookup in Python
This code demonstrates using collections.ChainMap to combine multiple dictionaries into a single layered lookup, where earlier maps override later ones.
from collections import ChainMap
defaults = {"theme": "light", "lang": "en", "debug": False}
user = {"lang": "de", "auto_save": True}
runtime = {"debug": True}
config = ChainMap(runtime, user, defaults)
if __name__ == "__main__":
print("theme:", config["theme"])
print("lang:", config["lang"])
print("deb…
How to Use a Frozenset as a Dict Key in Python
Demonstrates using an immutable frozenset as a hashable dictionary key, including equality and lookup with differently-ordered elements.
frozen = frozenset({"a", "b", "c"})
mapping = {frozen: "set as hashable key"}
other_frozen = frozenset(["c", "b", "a"])
print(f"Are keys equal? {frozen == other_frozen}")
print(f"Lookup with different order: {mapping[other_frozen]}")
print(f"Hash matches: {hash(frozen) == hash(other_frozen)}")
Merge Data with Comprehension and Generator in Python
Merge user and order data using a dictionary comprehension for lookups and a generator expression to filter and transform orders.
def merge_data(users, orders):
"""
Merge user and order data using a dictionary comprehension
and a generator expression for filtering.
"""
# Build a lookup: user_id -> user name
user_map = {user["id"]: user["name"] for user in users}
# Generator: yield orders with user names attached
…
Route Tool Call Name to Python Handler Dict
Routes a tool call name to the correct Python handler function using a dictionary lookup, returning an error for unknown tools.
def get_name():
return {"name": "Alice"}
def get_age():
return {"age": 30}
def get_email():
return {"email": "alice@example.com"}
handlers = {
"get_name": get_name,
"get_age": get_age,
"get_email": get_email,
}
def route(tool_call):
handler = handlers.get(tool_call["name"])
if handl…
How to Perform a DNS Lookup for A Records in Python
Resolve a hostname to IPv4 A records using Python's built-in socket.getaddrinfo and return a sorted list of addresses.
import socket
def get_a_records(hostname):
"""Fetch A records (IPv4 addresses) for a given hostname."""
try:
# getaddrinfo with family AF_INET restricts to IPv4 (A records)
infos = socket.getaddrinfo(hostname, None, socket.AF_INET)
# Each info tuple: (family, type, proto, canonname, so…
Enrich Events with Geo IP Data in Python
Returns a copy of each event dictionary, enriched with a geo-location dict from a mock IP-to-geo lookup table, with a fallback for unknown IPs.
import ipaddress
GEO_IP_DB = {
"192.168.1.10": {"country": "US", "city": "New York", "lat": 40.7128, "lon": -74.0060},
"10.0.0.5": {"country": "DE", "city": "Berlin", "lat": 52.5200, "lon": 13.4050},
"172.16.0.8": {"country": "JP", "city": "Tokyo", "lat": 35.6762, "lon": 139.6503},
}
EVENTS = [
{"id…
How to Mock a GraphQL Query Type in Python
Create a lightweight mock of a GraphQL Query type to simulate repository lookups without a server.
import json
class Query:
def __init__(self):
self.starred_repos = [
{"id": 1, "name": "graphql", "owner": "graphql"}
]
def repository(self, name):
if name == "graphql":
return {"id": 1, "name": "graphql", "stargazerCount": 85000}
return None
if __name…
Dedupe processed message IDs in Python
Filters an inbox of messages by removing items whose IDs have already been processed, using a set for fast lookups.
from pathlib import Path
import json
def dedupe_processed_ids(inbox_file: Path, processed_file: Path) -> list:
processed = set(json.loads(processed_file.read_text()))
inbox = json.loads(inbox_file.read_text())
deduped = [item for item in inbox if item["id"] not in processed]
return deduped
if __nam…
Simple Redis Cache Helper in Python
Build a minimal Redis-backed cache with TTL, JSON serialization, and automated fetching to speed up repeated expensive lookups.
import time
import redis
import json
class SimpleCache:
def __init__(self, host="localhost", port=6379, db=0, default_ttl=60):
self.client = redis.Redis(host=host, port=port, db=db, decode_responses=True)
self.default_ttl = default_ttl
def get(self, key):
value = self.client.get(key)…
How to Mock a Service Registry in Python with an In-Memory Dict
A lightweight ServiceRegistry class backed by a dict, exposing register, unregister, lookup, list, and health-check methods.
class ServiceRegistry:
def __init__(self):
self._services = {}
def register(self, name, endpoint, version="1.0"):
self._services[name] = {
"endpoint": endpoint,
"version": version,
"status": "healthy"
}
def unregister(self, name):
return…
How to Broadcast a Small Lookup Table in Python
Simulates broadcasting a small lookup table by iterating key-value pairs and emitting packed rows to subscribers with deterministic output.
import random
# Generate a deterministic mock broadcast of a small lookup table
# with 5 keys and random integer values (seeded for reproducibility)
data = {
"sensor_a": 22,
"sensor_b": 87,
"sensor_c": 43,
"sensor_d": 65,
"sensor_e": 31,
}
# Simulate a broadcast to subscribers by iterating and p…
How to Mock a Hash Join on Large and Small Tables in Python
This code efficiently joins a large dataset (1000 rows) with a small lookup table (20 rows) by building a dictionary hash lookup, mimicking a hash join strategy used in big data systems.
import random
from pprint import pprint
# Large table: 1000 rows (id, group_id, value)
large = [{"id": i, "group_id": random.randint(1, 20), "value": random.random() * 100} for i in range(1000)]
# Small table: 20 rows (group_id, label)
small = [{"group_id": g, "label": f"Group-{g}"} for g in range(1, 21)]
# Mock a …
How to Use Broadcast Variables as Read-Only in PySpark (Mock Example)
Share a lookup dict across Spark executors with a broadcast variable and verify its read-only behavior in a local mock.
from pyspark import SparkContext, SparkConf
def main():
conf = SparkConf().setAppName("BroadcastMock").setMaster("local[2]")
sc = SparkContext(conf=conf)
lookup = {"a": 1, "b": 2, "c": 3}
broadcast_lookup = sc.broadcast(lookup)
data = ["a", "b", "c", "a", "unknown"]
rdd = sc.parallel…
How to Mock a Feature Store Online Lookup in Python
This code simulates an online feature store with single and batch retrieval methods, using a dict-backed cache and timestamps.
import random
import time
class OnlineFeatureStore:
def __init__(self):
self.features = {}
def put(self, entity_id: str, feature_name: str, value):
key = (entity_id, feature_name)
self.features[key] = (value, time.time())
def get(self, entity_id: str, feature_name: str):
…
Broadcast a Small Reference Table in Python
Simulates SQL-style broadcasting of a small lookup table against a larger fact table in memory for mockups or load tests.
import random
def broadcast_mock(target, source, columns):
result = {}
for col in columns:
if col in target and col in source:
result[col] = target[col] + [source[col][i % len(source[col])] for i in range(len(target[col]))]
elif col in target:
result[col] = target[col]
…
Build a Partial Index Mock in Python for Database Filtering
Simulate a partial database index by filtering keys with a predicate, then return a limited mock lookup dictionary.
data = [
"alpha", "beta", "gamma", "delta", "epsilon",
"zeta", "eta", "theta", "iota", "kappa"
]
filtered_keys = [item for item in data if len(item) >= 5]
def mock_partial_index(keys, filter_func, limit=3):
result = {}
for key in keys:
if not filter_func(key):
continue
res…
Database indexing and query timing optimization in Python
Create SQLite indexes and time query performance to measure speedup for large table lookups in Python.
import sqlite3
import time
def time_query(db_path, query, params=()):
conn = sqlite3.connect(db_path)
conn.execute("PRAGMA journal_mode = WAL")
start = time.perf_counter()
result = conn.execute(query, params).fetchall()
elapsed = time.perf_counter() - start
conn.close()
return result, ela…
Hash index equality mock concept in Python
A simple hash index class in Python that stores key-value pairs in buckets and demonstrates basic equality-based lookup.
class HashIndex:
def __init__(self):
self._buckets = {}
def insert(self, key, value):
"""Insert a key-value pair into the hash index."""
index = hash(key) % 10
if index not in self._buckets:
self._buckets[index] = []
self._buckets[index].append((key, value))…
How to Speed Up Column Lookups with DataFrame Index in Python
Use pandas set_index to make repeated column value lookups O(1)-style fast instead of scanning the whole DataFrame each time.
import pandas as pd
# Mock dataset with duplicate customer IDs
data = {"customer_id": [101, 102, 103, 101, 104, 102],
"order_amount": [250.0, 85.5, 300.0, 175.25, 420.0, 95.75]}
df = pd.DataFrame(data)
df = df.set_index("customer_id")
# Simulated lookup request
search_id = 102
# Fast index-based lookup (no…
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.