Reference library

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

79 matches
Functions & basics easy

How to Sort a List of Dictionaries by Key with a Lambda in Python

Sort a list of dictionaries ascending or descending by one of their keys using sorted() with a lambda as the key function — a beginner-friendly pattern.

sorting lambda dictionaries
Python
def get_students():
    return [
        {"name": "alice", "score": 85},
        {"name": "bob", "score": 92},
        {"name": "carol", "score": 78},
        {"name": "dave", "score": 92},
    ]

students = get_students()

sorted_by_score = sorted(students, key=lambda s: s["score"])
print("Sorted by score (ascending)…
13 0 Open
Functions & basics easy

How to Use Lambda Sorting Keys in Python

Learn to sort lists of dictionaries using lambda functions as key arguments in Python's sorted() method.

lambda sorting beginner
Python
# Demonstrate lambda as a sorting key function

students = [
    {"name": "Alice", "grade": 88},
    {"name": "Bob", "grade": 92},
    {"name": "Charlie", "grade": 75},
    {"name": "Diana", "grade": 95}
]

# Sort by grade (ascending) using a lambda key
sorted_by_grade = sorted(students, key=lambda student: student["g…
15 0 Open
Errors & debugging medium

How to Diff Two Dicts in Python for Config Drift

Recursively compare two dictionaries and report added, removed, and changed keys with their old and new values for debugging configuration drift.

dict diff config
Python
def diff_dicts(a, b, path=""):
    differences = []

    for key in a.keys() | b.keys():
        new_path = f"{path}.{key}" if path else key

        if key not in a:
            differences.append((new_path, "<missing>", b[key], "added"))
        elif key not in b:
            differences.append((new_path, a[key], "<…
12 0 Open
Errors & debugging easy

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.

optional typing dict-get
Python
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…
15 0 Open
Errors & debugging easy

How to check for None and raise helpful errors in Python

A defensive function that explicitly validates data, keys, and values — raising descriptive ValueError and KeyError exceptions before returning a result.

none error-handling validation
Python
def get_value(data, key):
    if data is None:
        raise ValueError("data cannot be None")
    if key not in data:
        raise KeyError(f"key '{key}' not found in data")
    result = data[key]
    if result is None:
        raise ValueError(f"value for key '{key}' is None")
    return result


if __name__ == "__…
15 0 Open
Errors & debugging easy

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.

eafp lbyl dictionary
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")…
14 0 Open
Errors & debugging medium

Redact secrets from log message formatter in Python

Build a custom logging.Formatter that masks passwords, API keys, and credit card numbers in log output.

logging redaction security
Python
import re
import logging

class RedactingFormatter(logging.Formatter):
    """Formatter that masks sensitive data in log messages."""
    
    SENSITIVE_PATTERNS = [
        (re.compile(r'password[=:]\s*\S+', re.IGNORECASE), 'password=[REDACTED]'),
        (re.compile(r'api[_-]?key[=:]\s*\S+', re.IGNORECASE), 'api_key…
14 0 Open
Files & data easy

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.

json dict merge
Python
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,…
13 0 Open
Files & data easy

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.

json files serialization
Python
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…
14 0 Open
Dictionaries & sets medium

Build a Case-Insensitive Dict with a Wrapper Class in Python

Create a custom dict subclass that treats keys as case-insensitive by normalizing them to lowercase, with a full set of common dict methods.

dictionary case-insensitive wrapper
Python
class CaseInsensitiveDict:
    def __init__(self, data=None):
        self._data = {}
        if data:
            self.update(data)

    def __setitem__(self, key, value):
        self._data[str(key).lower()] = value

    def __getitem__(self, key):
        return self._data[str(key).lower()]

    def __delitem__(sel…
13 0 Open
Dictionaries & sets easy

Build an OrderedDict insertion order demo in Python 3

Demonstrate how OrderedDict preserves insertion order, how updates keep position, and how re-insertion moves keys to the end.

ordereddict dictionaries insertion-order
Python
from collections import OrderedDict

def demo_ordered_dict():
    # Create an OrderedDict and insert items in a specific order
    ordered = OrderedDict()
    ordered['banana'] = 3
    ordered['apple'] = 2
    ordered['cherry'] = 5
    ordered['date'] = 1

    print("Insertion order preserved:")
    for key, value in …
13 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

Filter Dictionary Keys by Prefix in Python

Use a dict comprehension to build a new dictionary containing only keys that start with a given prefix.

dict-comprehension filtering dictionaries
Python
def filter_dict_keys(data, prefix="temp_"):
    """
    Filter a dictionary by keeping only keys that start with a given prefix.
    Uses a dict comprehension to build a new dictionary.
    """
    if not isinstance(data, dict):
        raise ValueError("data must be a dictionary")
    return {key: value for key, valu…
13 0 Open
Dictionaries & sets medium

Find All Leaf Paths in a Nested Dict in Python

Recursively traverse a nested dictionary and yield every leaf path as a list of keys, including paths to empty dictionaries.

dictionary recursion nested-data
Python
def find_leaf_paths(data, path=None):
    if path is None:
        path = []
    
    if not isinstance(data, dict) or not data:
        yield path
        return
    
    for key, value in data.items():
        yield from find_leaf_paths(value, path + [key])

if __name__ == "__main__":
    nested = {
        "a": 1,
…
13 0 Open
Dictionaries & sets easy

Flatten a Nested Dict to Dot Notation Keys in Python

Recursively flatten a nested dictionary into a flat dictionary with dot-separated keys using a small recursive function.

dict flatten recursion
Python
def flatten_dict(nested, parent_key='', sep='.'):
    items = {}
    for key, value in nested.items():
        new_key = f"{parent_key}{sep}{key}" if parent_key else key
        if isinstance(value, dict):
            items.update(flatten_dict(value, new_key, sep))
        else:
            items[new_key] = value
    …
11 0 Open
Dictionaries & sets medium

How to Build a TTL Cache Dict in Python

Create a dictionary subclass that automatically expires keys after a fixed time-to-live using timestamps.

dictionary cache ttl
Python
import time

class TTLDict(dict):
    def __init__(self, ttl, *args, **kwargs):
        self.ttl = ttl
        self._expires = {}
        super().__init__(*args, **kwargs)

    def __setitem__(self, key, value):
        super().__setitem__(key, value)
        self._expires[key] = time.time() + self.ttl

    def __geti…
16 0 Open
Dictionaries & sets easy

How to Diff Two Dicts in Python: Added, Removed, and Changed Keys

Compare two dictionaries and report added, removed, and changed keys using Python's set operations on dict keys.

dict diff set-operations
Python
def diff_dicts(old: dict, new: dict) -> dict:
    """Compare two dicts and report added, removed, and changed keys."""
    added = {k: new[k] for k in new.keys() - old.keys()}
    removed = {k: old[k] for k in old.keys() - new.keys()}

    common_keys = old.keys() & new.keys()
    changed = {k: (old[k], new[k]) for k …
15 0 Open
Dictionaries & sets easy

How to Find Keys with Matching Values in Two Dictionaries in Python

Find dictionary keys where both dictionaries have the exact same value by iterating over key-value pairs and comparing them.

dictionaries comparison data-matching
Python
def find_matching_values(dict1, dict2):
    """Return list of keys that have the same value in both dicts."""
    matches = []
    for key, value in dict1.items():
        if key in dict2 and dict2[key] == value:
            matches.append(key)
    return matches


if __name__ == "__main__":
    # Example usage
    di…
13 0 Open
Dictionaries & sets easy

How to Invert a Dictionary in Python Safely

Swap dictionary keys and values while detecting duplicate values to prevent silent data loss.

dictionary inversion data-safety
Python
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,…
15 0 Open
Dictionaries & sets easy

How to Merge Dictionaries and Find Unique Keys in Python

Merge two dictionaries with update(), then use sets to find all unique keys and the keys shared between both dictionaries.

dictionaries sets merge
Python
def merge_and_unique(dict1, dict2):
    merged = dict1.copy()
    merged.update(dict2)
    unique_keys = set(merged.keys())
    common_keys = set(dict1.keys()) & set(dict2.keys())
    return merged, unique_keys, common_keys


if __name__ == "__main__":
    fruits = {"apple": 3, "banana": 5, "orange": 2}
    more_fruit…
14 0 Open
Dictionaries & sets easy

How to Merge Two Dictionaries in Python with the Spread Operator

Merge two Python dictionaries into one new dict using the ** unpacking (spread) operator, with later keys overriding earlier ones.

dicts merge spread-operator
Python
def merge_two_dicts(dict1: dict, dict2: dict) -> dict:
    """Merge two dictionaries using the spread operator pattern."""
    # The ** operator unpacks key-value pairs, later keys overwrite earlier ones
    merged = {**dict1, **dict2}
    return merged


if __name__ == "__main__":
    # Example usage with overlapping…
15 0 Open
Dictionaries & sets easy

How to Normalize Data in Python with Dictionaries and Sets

Normalize a list of dicts by keeping selected keys, stripping/lowercasing strings, and extracting unique sorted values using set comprehension.

dictionaries sets data-cleaning
Python
def normalize_data(data, keys):
    """
    Normalize a list of dictionaries by keeping only specified keys
    and converting values to proper types.
    """
    normalized = []
    for item in data:
        clean_item = {}
        for key in keys:
            value = item.get(key)
            if isinstance(value, st…
12 0 Open
Dictionaries & sets easy

How to Normalize Data with Dictionaries and Sets in Python

Normalize dictionary entries to a fixed set of keys and extract unique values using sets in Python.

dictionaries sets data-cleaning
Python
def normalize_entry(entry: dict, valid_keys: set) -> dict:
    result = {}
    for key in valid_keys:
        result[key] = entry.get(key, "")
    return result


def unique_values(entries: list[dict], key: str) -> set:
    return {entry.get(key) for entry in entries if entry.get(key) is not None}


if __name__ == "__…
14 0 Open
Dictionaries & sets easy

How to Parse Query String to Dict with Duplicate Keys in Python

Convert a URL query string into a Python dictionary, merging duplicate keys into lists while keeping single values as scalars.

query-string dict url-parsing
Python
from urllib.parse import parse_qs


def parse_query_to_dict(query_string):
    parsed = parse_qs(query_string, keep_blank_values=True)
    return {key: values if len(values) > 1 else values[0] for key, values in parsed.items()}


if __name__ == "__main__":
    query = "name=John&name=Jane&age=30&city=&city=Paris&empty…
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.