Python Code Snippets
Python Code Snippets
Section titled “Python Code Snippets”This page collects short examples that are actually useful in day-to-day Python work.
Loop Through a List
Section titled “Loop Through a List”items = ["api", "worker", "scheduler"]
for item in items: print(item)Build a Dictionary Safely
Section titled “Build a Dictionary Safely”user = { "name": "Ava", "role": "admin", "active": True,}
print(user["name"])Count Frequencies
Section titled “Count Frequencies”from collections import Counter
values = ["python", "python", "api", "docs"]counts = Counter(values)
print(counts)Read a Text File
Section titled “Read a Text File”with open("notes.txt", "r", encoding="utf-8") as file: content = file.read()
print(content)Write JSON to Disk
Section titled “Write JSON to Disk”import json
payload = {"status": "ok", "items": 3}
with open("output.json", "w", encoding="utf-8") as file: json.dump(payload, file, indent=2)Handle an Expected Exception
Section titled “Handle an Expected Exception”try: value = int("42")except ValueError: value = 0
print(value)Read an Environment Variable
Section titled “Read an Environment Variable”import os
api_key = os.getenv("OPENAI_API_KEY")
if not api_key: raise RuntimeError("OPENAI_API_KEY is not set")Filter a List
Section titled “Filter a List”numbers = [1, 2, 3, 4, 5, 6]even_numbers = [number for number in numbers if number % 2 == 0]
print(even_numbers)