Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Group Data by Category in Python
Group a list of (category, value) tuples into a dictionary of lists using the setdefault method.
def group_by_category(data):
"""Group list of (category, value) tuples into dictionaries of lists."""
groups = {}
for category, value in data:
groups.setdefault(category, []).append(value)
return groups
if __name__ == "__main__":
items = [
("fruit", "apple"),
("veg", "carro…
How to Sort a List of Dictionaries by a Key in Python
Sort a list of dictionaries by a specified key field, optionally in descending order, using Python's built-in sorted() function.
def sort_dicts_by_key(data, key, reverse=False):
return sorted(data, key=lambda item: item.get(key), reverse=reverse)
if __name__ == "__main__":
people = [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 25},
{"name": "Charlie", "age": 35},
]
sorted_by_age = sort_dicts_b…
How to Summarize a List of Numbers in Python
Loop over a list of numbers to compute total, count, average, min, and max, then return them in a dictionary.
def summarize_numbers(numbers):
"""Return a dict with basic stats for a list of numbers."""
total = 0
count = 0
smallest = numbers[0]
largest = numbers[0]
for num in numbers:
total += num
count += 1
if num < smallest:
smallest = num
if num > largest:…
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…
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"{…
How to Catch KeyError with a Default Value in Python Dictionaries
Safely retrieve dictionary values while catching KeyError and handling None values by returning a default.
def get_value(data, key, default=None):
"""
Safely get a value from a dictionary, returning a default if the key
is missing or the value is None.
"""
try:
value = data[key]
return value if value is not None else default
except KeyError:
return default
if __name__ == "_…
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.
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], "<…
Use pprint for Nested Structure Debug Output in Python
Pretty-print nested dictionaries and lists with pprint for readable, organized debug output.
from pprint import pprint
def build_nested_structure():
"""Create a sample nested data structure for demonstration."""
return {
"project": "DataPipeline",
"config": {
"inputs": ["raw_1.json", "raw_2.json"],
"processing": {
"steps": ["clean", "transform",…
Export List of Dicts to CSV in Python
Write a list of dictionaries (dataframe-like) to a CSV file with headers using the standard library csv module and verify by reading it back.
import csv
def export_to_csv(data, filename):
"""Export a list of dicts to a CSV file."""
if not data:
print("No data to export")
return
# Get column names from the keys of the first dict
fieldnames = list(data[0].keys())
with open(filename, 'w', newline='', encoding='utf…
How to Build a CSV Comparison Tool That Highlights Every Changed Cell in Python
Read two CSV files with DictReader, compare cell by cell, and return a list of dictionaries describing each changed cell using only the standard library.
import csv
from pathlib import Path
def csv_cell_diff(file_a: str, file_b: str) -> list[dict]:
rows_a = list(csv.DictReader(Path(file_a).open('r', newline='')))
rows_b = list(csv.DictReader(Path(file_b).open('r', newline='')))
if not rows_a or not rows_b:
return []
columns = list(rows_a[0].key…
How to List File Information in a Directory with Python
A helper that walks a directory and returns each file's name, size, and extension as a list of dictionaries.
from pathlib import Path
def get_files_data(directory: str) -> list[dict]:
"""Return basic info about all files in a directory."""
files = []
for path in Path(directory).iterdir():
if path.is_file():
files.append({
"name": path.name,
"size": path.stat()…
How to Merge Environment-Specific Config JSON in Python
Loads a base JSON config and overlays environment-specific overrides, merging the two dictionaries into one final config.
import json
import pathlib
def load_config(base_path: pathlib.Path, env: str) -> dict:
base_config = json.loads(base_path.read_text())
env_path = base_path.with_name(f"config.{env}.json")
if env_path.exists():
env_config = json.loads(env_path.read_text())
return {**base_config, **env_conf…
How to Parse Apache Log Files in Python
Parse Apache common log format lines into structured dictionaries using Python's standard library.
import re
from pathlib import Path
def parse_apache_line(line):
pattern = r'^(\S+) (\S+) (\S+) \[([^\]]+)\] "(\S+) (\S+) (\S+)" (\d{3}) (\S+)'
match = re.match(pattern, line)
if not match:
return None
ip, ident, user, timestamp, method, path, protocol, status, size = match.groups()
return …
How to Read a TSV File in Python with csv.DictReader
Read a tab-separated (TSV) file into dictionaries using the csv module's DictReader with a tab delimiter.
import csv
from pathlib import Path
data_file = Path("data.tsv")
# Sample TSV content (tab-separated)
sample = """name\tage\tcity
Alice\t30\tNew York
Bob\t25\tLos Angeles
Carol\t35\tChicago
"""
data_file.write_text(sample)
with data_file.open("r", newline="", encoding="utf-8") as f:
reader = csv.DictReader(f, d…
How to Sort Files by Name and Size in Python
Sort a list of file dictionaries by name then size using Python's sorted() with a lambda key.
from pathlib import Path
def sort_files_data(files):
"""Sort a list of file dictionaries by name, then by size."""
return sorted(files, key=lambda f: (f["name"], f["size"]))
if __name__ == "__main__":
files_data = [
{"name": "report.pdf", "size": 2048},
{"name": "data.csv", "size": 1024},…
Read SQLite database with sqlite3 module in Python
Connect to a SQLite database and query rows with the standard library sqlite3 module, returning results as dictionaries.
import sqlite3
from pathlib import Path
# Create an in-memory database and a sample table
connection = sqlite3.connect(":memory:")
cursor = connection.cursor()
cursor.execute("""
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
department TEXT NOT NULL,
salary REAL
)
""")
# Inser…
Read a CSV File with csv.DictReader in Python
Read a CSV file as a list of dictionaries, using csv.DictReader to map each row to column names.
import csv
from pathlib import Path
def read_csv_with_dictreader(file_path):
data = []
with open(file_path, mode='r', newline='', encoding='utf-8') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
data.append(row)
return data
if __name__ == "__main__":
# Cre…
Write CSV file with csv DictWriter in Python
Write a list of dictionaries to a CSV file using Python's csv.DictWriter, including a header row.
import csv
from pathlib import Path
fieldnames = ["name", "city", "age"]
rows = [
{"name": "Alice", "city": "New York", "age": 30},
{"name": "Bob", "city": "Los Angeles", "age": 25},
{"name": "Charlie", "city": "Chicago", "age": 35},
]
path = Path("people.csv")
with path.open("w", newline="") as csvfile:…
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.
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 …
Compare Two Dictionaries in Python
Compare two dictionaries by finding common keys, unique keys, and value differences using Python's set operations.
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…
Convert Lists and Dictionaries to Sets in Python
Convert lists of pairs into dictionaries and lists or dictionaries into sets using simple helper functions.
def convert_to_dict(data):
"""Convert list of tuples or lists into a dictionary."""
return dict(data)
def convert_to_set(data):
"""Convert list or dictionary into a set of its keys/values."""
if isinstance(data, dict):
return set(data.keys())
return set(data)
def convert_collection(data…
Count Words in Python with Dictionaries and Sets
Text analysis example that counts total words, finds unique words with a set, and tallies character frequencies with a dictionary.
def analyze_text(text: str) -> dict:
"""Count words, find unique words, and show common characters."""
words = text.lower().split()
word_count = len(words)
unique_words = set(words)
char_counts = {}
for word in words:
for char in word:
if char.isalpha():
…
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.
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…
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.