Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
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…
How to Sort Dictionary Keys Alphabetically in Python
This code returns a list of dictionary keys sorted alphabetically, using a case-insensitive comparison while preserving the original insertion order for keys that are equal.
data = {
"banana": 3,
"apple": 1,
"Cherry": 5,
"date": 2,
"apple": 4,
"Fig": 6,
"banana": 2,
}
def sort_dict_keys_alphabetically(d):
"""Return a list of keys sorted alphabetically (case-insensitive), stable for duplicates."""
return sorted(d.keys(), key=lambda k: k.lower())
if __n…
How to Sort a List of Dictionaries by Key in Python
Sort a list of dictionaries by various keys (grade, age, name) using lambda, itemgetter, and extract unique sorted names into a set.
from operator import itemgetter
# Sample data: a list of dictionaries representing students
students = [
{"name": "Alice", "grade": 88, "age": 23},
{"name": "Bob", "grade": 95, "age": 22},
{"name": "Charlie", "grade": 78, "age": 24},
{"name": "Diana", "grade": 92, "age": 21}
]
# Sort by grade (descen…
How to Validate Required Dict Keys in Python
Check whether a dictionary contains all required keys and return the list of missing ones using a simple list comprehension.
def find_missing_keys(data: dict, required_keys: list) -> list:
"""Return a list of required keys that are missing from the dictionary."""
return [key for key in required_keys if key not in data]
if __name__ == "__main__":
user_data = {
"name": "Alice",
"email": "alice@example.com",
…
How to swap dict keys and values in Python when values are unique
Swap dict keys and values using a dict comprehension, with a guard that raises an error when values repeat.
def swap_dict_keys_values(d):
"""Swap keys and values in a dict, assuming values are unique."""
if len(set(d.values())) != len(d.values()):
raise ValueError("Values must be unique to swap keys and values")
return {v: k for k, v in d.items()}
if __name__ == "__main__":
original = {"a": 1, "b": …
Unflatten Dot Keys to Nested Dict in Python
Convert a flat dictionary with dot-separated keys into a nested dictionary structure using recursive setdefault loops.
def unflatten_dot_keys(flat_dict):
result = {}
for flat_key, value in flat_dict.items():
parts = flat_key.split(".")
current = result
for part in parts[:-1]:
current = current.setdefault(part, {})
current[parts[-1]] = value
return result
if __name__ == "__main_…
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(…
How to Make a Python Class Hashable with __eq__ and __hash__
Define __eq__ and __hash__ together on a Python class so equal instances share the same hash and work correctly in sets and dictionary keys.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
if not isinstance(other, Point):
return NotImplemented
return self.x == other.x and self.y == other.y
def __hash__(self):
return hash((self.x, self.y))
def __repr…
How to Detect Hardcoded Secrets in Python Source Code
A Python utility that scans source code for common hardcoded secrets like API keys, passwords, tokens, and AWS credentials using regex patterns.
import re
def detect_secrets(text):
"""Detect potential hardcoded secrets in source code."""
patterns = {
'api_key': r'(?i)(api[_-]?key|apikey)\s*[=:]\s*["\']([^"\']+)["\']',
'password': r'(?i)(password|passwd)\s*[=:]\s*["\']([^"\']+)["\']',
'token': r'(?i)(\b(token|secret)\b)\s*[=:]\s…
Sort list by multiple keys with tuple ordering in Python
Sort a list of dictionaries by multiple criteria — surname, age, then score descending — using a tuple key and negation.
def sort_multi_key(data):
# Sorts by surname, then age, then score descending
return sorted(
data,
key=lambda person: (
person['surname'].lower(),
person['age'],
-person['score'] # negative to reverse sort by score
)
)
if __name__ == "__main__"…
Stable sort preserving equal order demo in Python
Demonstrates Python's stable sort, showing that elements with equal sort keys retain their original relative order.
from operator import itemgetter
def stable_sort_demo():
data = [(3, "first"), (1, "second"), (3, "third"), (1, "fourth"), (2, "fifth")]
print("Original:", data)
# Sort by first element (the tuple's first value), keeping relative order of equal items
sorted_data = sorted(data, key=itemgetter(0))
…
Dict Comprehension to Map Keys to Lengths in Python
Build a dictionary that maps each word to its character count using a dictionary comprehension.
words = ["apple", "banana", "cherry", "date", "elderberry"]
word_lengths = {word: len(word) for word in words}
print(word_lengths)
Group Consecutive Keys in Python with itertools.groupby
Group consecutive equal elements in a list using the itertools.groupby generator, printing each key and its values.
from itertools import groupby
data = [1, 1, 2, 2, 3, 1, 1, 4, 4, 4]
for key, group in groupby(data):
group_list = list(group)
print(f"Key: {key}, Values: {group_list}")
JSON Mode Prompt Schema Output in Python
Extract a user object to JSON with explicit schema keys, ready for LLM JSON-mode prompts.
import json
from typing import Any, Dict
def extract_user_as_json(user: Dict[str, Any]) -> str:
"""Extract a user object and return it as JSON using explicit schema keys."""
schema_fields = ("id", "name", "email", "is_active")
user_subset = {key: user[key] for key in schema_fields if key in user}
ret…
Find Sensitive Information in Log Files with Python
Scan log files for emails, IP addresses, API keys, and passwords using regular expressions in Python.
import re
import os
from pathlib import Path
def find_sensitive_info(log_path):
"""Scans log files for patterns like emails, IPs, API keys, and passwords."""
patterns = {
'Email': r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}',
'IP Address': r'\b(?:\d{1,3}\.){3}\d{1,3}\b',
'API Key'…
Generate Strong SSH Keys and Save Them Securely with Python
Generate a 4096-bit RSA SSH key pair using Python's cryptography library and save both private and public keys with restricted file permissions.
import os
import stat
from pathlib import Path
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends import default_backend
def generate_ssh_keypair(key_path: str = "id_rsa", passphrase: str = None):
"""Generate a 4096-…
Rotate API keys in Python by updating an .env template
Replace an old API key with a new one inside an .env template file, with a guard for missing keys.
import json
from pathlib import Path
def rotate_api_keys(env_template_path: Path, old_key: str, new_key: str) -> None:
"""Replace an old API key with a new one in an .env template file."""
content = env_template_path.read_text()
if old_key not in content:
print(f"Error: '{old_key}' not found in {e…
ETL in Python: Extract CSV, Transform Dicts, Load JSON
Build a simple ETL pipeline that reads a CSV, normalizes keys and converts price to float, then writes structured JSON.
import csv
import json
from pathlib import Path
def etl_csv_to_json(csv_path: str, json_path: str) -> None:
"""Extract CSV, transform rows to dicts, load to JSON."""
with open(csv_path, mode='r', newline='', encoding='utf-8') as f:
reader = csv.DictReader(f)
records = list(reader)
# Trans…
How to Clean and Format Data in Python
This code loads JSON data, cleans records by removing empty fields and normalizing text, then summarizes the results with counts and unique keys.
import json
from pathlib import Path
def load_data(filepath: str) -> dict:
"""Load JSON data from a file."""
with Path(filepath).open("r", encoding="utf-8") as f:
return json.load(f)
def clean_records(records: list[dict]) -> list[dict]:
"""Remove empty fields and normalize text to lowercase."""…
How to Implement SCD Type 1 Overwrite in Python with SQLite
Implement SCD Type 1 dimension updates in Python using SQLite — overwrite existing rows with new data while preserving keys.
import sqlite3
# Simulate a dimension table with SCD Type 1 (overwrite)
conn = sqlite3.connect(":memory:")
cursor = conn.cursor()
# Create dimension table
cursor.execute("""
CREATE TABLE customer_dim (
customer_id INTEGER PRIMARY KEY,
customer_name TEXT,
city TEXT,
updated_at TEXT…
Test a Python Pipeline with Fixture Sample Rows
Test pipeline functions with sample rows provided by a pytest fixture, verifying required keys and value constraints.
import pytest
def get_value(data: dict, key: str):
return data.get(key)
def sample_rows():
return [
{"name": "Alice", "age": 30, "city": "London"},
{"name": "Bob", "age": 25, "city": "Paris"},
{"name": "Charlie", "age": 35, "city": "Berlin"},
]
@pytest.fixture
def sample_data(…
Build a Simple Log Graph in Python
Create a basic one-dimensional bar chart from log lines by counting occurrences of leading numeric keys.
import heapq
def log_graph(log_lines: list[str]) -> str:
"""Build a simple per-line, one-dimensional visual graph from log entries."""
counts: dict[int, int] = {}
for line in log_lines:
tokens = line.split()
if tokens:
try:
idx = int(tokens[0])
exce…
Mock S3 List Objects Paginator in Python
This code implements a mock S3 paginator that yields pages of object keys, mimicking the behavior of boto3's list_objects_v2 paginator for local testing.
import json
from datetime import datetime, timezone
class MockS3Paginator:
"""A mock S3 list_objects_v2 paginator returning pages of keys."""
def __init__(self, bucket, all_keys, page_size=1000):
self.bucket = bucket
self.all_keys = all_keys
self.page_size = page_size
def pagina…
How to Bind and Mock structlog Context in Python
Shows how to bind persistent key-value context to a structlog logger, unbind keys, and mock the logger in tests to verify context is passed correctly.
import structlog
from unittest.mock import patch
logger = structlog.get_logger()
def demo():
logger = structlog.get_logger()
logger = logger.bind(user_id=42, request_id="abc123")
logger.info("user logged in", action="login")
# Unbind a key
logger = logger.unbind("user_id")
logger.info("r…
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.