Functions & basics
Reusable building blocks — parameters, returns, scope, and clear function design.
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 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.
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)…
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.
# 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…
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…
Sort a List of Dictionaries by Key in Python
Uses a lambda function with sorted() to order a list of dictionaries by a specified key, like price.
def get_items():
return [
{"name": "apple", "price": 3},
{"name": "banana", "price": 1},
{"name": "cherry", "price": 2},
]
if __name__ == "__main__":
items = get_items()
sorted_items = sorted(items, key=lambda item: item["price"])
for item in sorted_items:
print(f"{…
Browse by section
Each section groups closely related Python snippets.
Functions & basics — Python code examples
What you will find here
This page collects functions & basics snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
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.