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)