Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Parse Data Into Dictionaries and Sets in Python
Parses raw student strings into a dictionary of lists and finds unique courses using a set.
from collections import defaultdict
def parse_students(raw_data):
"""Parse raw student strings into a dictionary of lists."""
parsed = defaultdict(list)
for entry in raw_data:
name, _, course = entry.partition(":")
parsed[course.strip()].append(name.strip())
return dict(parsed)
def fi…
How to Recursively Remove None Values from Nested Dictionaries in Python
Recursively removes all None values from nested dictionaries and lists while preserving non-None data.
def prune_none(obj):
if isinstance(obj, dict):
return {
k: prune_none(v)
for k, v in obj.items()
if v is not None and prune_none(v) is not None
}
elif isinstance(obj, list):
pruned = [prune_none(item) for item in obj]
pruned = [item for item i…
How to Sort a List of Dictionaries by Key in Python
Sort a list of dictionaries by various keys (grade, age, name) using lambda, itemgetter, and extract unique sorted names into a set.
from operator import itemgetter
# Sample data: a list of dictionaries representing students
students = [
{"name": "Alice", "grade": 88, "age": 23},
{"name": "Bob", "grade": 95, "age": 22},
{"name": "Charlie", "grade": 78, "age": 24},
{"name": "Diana", "grade": 92, "age": 21}
]
# Sort by grade (descen…
How to Subtract Counters in Python for Bag Differences
Use the Counter class's subtraction operator to compute bag differences, removing items and counts that appear in one multiset but not the other.
from collections import Counter
def subtract_counters(bag1, bag2):
"""Return the difference of two Counters (bag1 - bag2)."""
return bag1 - bag2
if __name__ == "__main__":
inventory = Counter(apples=10, bananas=5, oranges=3)
sold = Counter(apples=4, bananas=2, grapes=2)
remaining = subtract_count…
How to Transform a List of Dictionaries with Sets in Python
Normalize a list of dict records — cleaning names, extracting unique tags with sets, and building a standardized result.
def transform_data(raw_records):
"""Transform a list of dict records into normalized data with sets for unique values."""
normalized = []
unique_names = set()
all_tags = set()
for record in raw_records:
# Normalize name to lowercase and strip whitespace
name = record.get("name"…
How to Use ChainMap for Layered Config Lookup in Python
This code demonstrates using collections.ChainMap to combine multiple dictionaries into a single layered lookup, where earlier maps override later ones.
from collections import ChainMap
defaults = {"theme": "light", "lang": "en", "debug": False}
user = {"lang": "de", "auto_save": True}
runtime = {"debug": True}
config = ChainMap(runtime, user, defaults)
if __name__ == "__main__":
print("theme:", config["theme"])
print("lang:", config["lang"])
print("deb…
How to Use Dictionaries and Sets in Python for Beginners
Demonstrates Python dictionary operations and set operations with examples, including access, modification, defaults, and set algebra.
def demonstrate_collections():
# Dictionary basics
student = {
"name": "Alice",
"age": 20,
"courses": ["Math", "Physics"]
}
print("Dictionary:", student)
# Access and modify
student["age"] = 21
student["grade"] = "A"
print("Modified:", student)
# Get with d…
How to Use Dictionaries and Sets in Python for Beginners
Introduces Python dictionaries and sets with practical examples including creating, modifying, and performing set operations, plus a word-frequency counter.
def demonstrate_dict_sets():
# Create a dictionary with basic info
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}
print("Dictionary:", person)
# Access and modify dictionary values
person["age"] = 31
person["email"] = "alice@example.com"
print("Afte…
How to Use defaultdict(list) to Group Words by First Letter in Python
This code groups a list of words by their first letter using a defaultdict with a list factory, then prints each group sorted by initial.
from collections import defaultdict
def group_by_initial(words):
groups = defaultdict(list)
for word in words:
groups[word[0].upper()].append(word)
return dict(groups)
if __name__ == "__main__":
words = ["apple", "banana", "apricot", "blueberry", "cherry"]
result = group_by_initial(words)…
How to Use defaultdict(set) in Python to Group Unique Values
Group key-value pairs into a dictionary of sets, automatically creating a new set for each key using defaultdict.
from collections import defaultdict
def track_groups(pairs):
groups = defaultdict(set)
for key, value in pairs:
groups[key].add(value)
return groups
if __name__ == "__main__":
data = [
("fruit", "apple"),
("fruit", "banana"),
("fruit", "apple"),
("veg", "carrot…
How to Validate Text and Count Words in Python
Count word frequencies, find unique and repeated words in a text using Python dictionaries and sets for beginner text validation.
def validate_text(text):
words = text.lower().split()
word_counts = {}
for word in words:
cleaned = word.strip('.,!?;:"\'')
if cleaned:
word_counts[cleaned] = word_counts.get(cleaned, 0) + 1
unique_words = set(word_counts.keys())
repeated_words = {word for word…
How to count words and find unique words in Python
Build a beginner-friendly text processor that counts word frequencies, finds unique words, and identifies words with vowels using dictionaries and sets.
def text_processor(text):
words = text.lower().replace(",", "").replace(".", "").split()
word_count = {}
for word in words:
word_count[word] = word_count.get(word, 0) + 1
unique_words = set(words)
vowels = set("aeiou")
words_with_vowels = {word for word in unique_words if vowe…
How to merge dictionaries and sets in Python
Merges multiple dictionaries with the ** unpacking operator and combines sets using union operations into a single structure.
def merge_dictionaries_and_sets(school_dict, teacher_dict, course_dict, student_sets):
"""
Merges multiple dictionaries and sets into a single combined structure.
Demonstrates dict unpacking and set union operations.
"""
# Merge all dictionaries using the unpacking operator (Python 3.9+)
merged…
Text Processor with Dictionaries and Sets in Python
Build a simple text processor that counts word frequencies with a dictionary and tracks unique words with a set.
def analyze_text(text):
words = text.lower().split()
word_freq = {}
unique_words = set()
for word in words:
clean_word = word.strip('.,!?;:')
if clean_word:
word_freq[clean_word] = word_freq.get(clean_word, 0) + 1
unique_words.add(clean_word)
return…
Unflatten Dot Keys to Nested Dict in Python
Convert a flat dictionary with dot-separated keys into a nested dictionary structure using recursive setdefault loops.
def unflatten_dot_keys(flat_dict):
result = {}
for flat_key, value in flat_dict.items():
parts = flat_key.split(".")
current = result
for part in parts[:-1]:
current = current.setdefault(part, {})
current[parts[-1]] = value
return result
if __name__ == "__main_…
Validate dictionary data with sets in Python
Validate a dictionary against required keys and allowed value sets, returning a list of validation errors.
def validate_data(data, required_keys, allowed_values=None):
"""
Validate a dictionary against required keys and optional allowed value sets.
Returns a list of validation errors (empty list if valid).
"""
errors = []
# Check for missing required keys
missing = set(required_keys) - set(…
Filtering data with a Python class helper
A beginner-friendly DataFilter class that filters lists of dictionaries by exact match, greater-than, and substring conditions.
class DataFilter:
"""A beginner-friendly helper to filter lists of dictionaries."""
def __init__(self, data):
self.data = data
def filter_by(self, key, value):
"""Return items where data[key] == value."""
return [item for item in self.data if item.get(key) == value]
…
How to Create a Data Formatter Class in Python
A beginner-friendly helper class to format lists, dictionaries, and stored records into readable strings.
class DataFormatter:
"""Helper class for beginners to format common data types."""
def __init__(self, name="data"):
self.name = name
self.records = []
def add_record(self, key, value):
"""Add a key-value record to the formatter."""
self.records.append({"key": key, …
How to Sort Data in Python with a Class Helper
This beginner-friendly class wraps the built-in sorted() function to sort numbers, strings ignoring case, and dictionaries by a specified key.
class DataSorter:
def __init__(self, data):
self.data = data
def sort_numbers(self, reverse=False):
return sorted(self.data, reverse=reverse)
def sort_strings_ignore_case(self, reverse=False):
return sorted(self.data, key=str.lower, reverse=reverse)
def sort_dicts_by_key(self…
How to merge dictionaries by a key in Python with a class
This code defines a DataMerger class that collects dictionary records and merges them by a specified key, combining fields from multiple records with the same key.
class DataMerger:
def __init__(self):
self.records = []
def add_record(self, record):
if isinstance(record, dict):
self.records.append(record)
else:
raise TypeError("Record must be a dictionary")
def merge_by_key(self, key):
merged = {}
for …
How to Flatten List of Dict Values in Python
This code flattens the values of a list of dictionaries into a single list, handling both list values and scalar values.
def flatten_dict_values(dicts):
flattened = []
for d in dicts:
for value in d.values():
if isinstance(value, list):
flattened.extend(value)
else:
flattened.append(value)
return flattened
if __name__ == "__main__":
data = [
{"a": …
Sort list by multiple keys with tuple ordering in Python
Sort a list of dictionaries by multiple criteria — surname, age, then score descending — using a tuple key and negation.
def sort_multi_key(data):
# Sorts by surname, then age, then score descending
return sorted(
data,
key=lambda person: (
person['surname'].lower(),
person['age'],
-person['score'] # negative to reverse sort by score
)
)
if __name__ == "__main__"…
How to Group Data in Python with defaultdict and Comprehensions
Group a list of items by a computed key using a defaultdict-based generator helper and an alternative dictionary comprehension approach.
from collections import defaultdict
def group_by(data, key_func):
"""Group items in data by the value returned by key_func."""
result = defaultdict(list)
for item in data:
result[key_func(item)].append(item)
return dict(result)
def group_by_comprehension(data, key_func):
"""Same grouping …
How to Use List Comprehensions and Generators to Format Data in Python
A beginner-friendly helper that formats dictionaries into strings using a list comprehension and generates squared numbers lazily with a generator.
def format_data(items):
"""Format a list of dictionaries into readable strings."""
formatted = [
f"{item.get('name', 'Unknown')}: {item.get('value', 0)} units"
for item in items
if item.get('value', 0) > 0
]
return formatted if formatted else ["No positive values found"]
def g…
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.