Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Merge Dictionaries and Find Unique Keys in Python
Merge two dictionaries with update(), then use sets to find all unique keys and the keys shared between both dictionaries.
def merge_and_unique(dict1, dict2):
merged = dict1.copy()
merged.update(dict2)
unique_keys = set(merged.keys())
common_keys = set(dict1.keys()) & set(dict2.keys())
return merged, unique_keys, common_keys
if __name__ == "__main__":
fruits = {"apple": 3, "banana": 5, "orange": 2}
more_fruit…
How to Normalize Data in Python with Dictionaries and Sets
Normalize a list of dicts by keeping selected keys, stripping/lowercasing strings, and extracting unique sorted values using set comprehension.
def normalize_data(data, keys):
"""
Normalize a list of dictionaries by keeping only specified keys
and converting values to proper types.
"""
normalized = []
for item in data:
clean_item = {}
for key in keys:
value = item.get(key)
if isinstance(value, st…
How to Normalize Data with Dictionaries and Sets in Python
Normalize dictionary entries to a fixed set of keys and extract unique values using sets in Python.
def normalize_entry(entry: dict, valid_keys: set) -> dict:
result = {}
for key in valid_keys:
result[key] = entry.get(key, "")
return result
def unique_values(entries: list[dict], key: str) -> set:
return {entry.get(key) for entry in entries if entry.get(key) is not None}
if __name__ == "__…
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 Remove Banned Words from a Set in Python
Filter a vocabulary set by removing banned words using the .difference() method.
vocabulary = {"apple", "banana", "cherry", "date", "elderberry"}
banned_words = {"banana", "date", "fig"}
# Remove banned words using set difference
allowed_words = vocabulary.difference(banned_words)
print("Original vocabulary:", sorted(vocabulary))
print("Banned words:", sorted(banned_words))
print("Allowed words …
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 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 a Frozenset as a Dict Key in Python
Demonstrates using an immutable frozenset as a hashable dictionary key, including equality and lookup with differently-ordered elements.
frozen = frozenset({"a", "b", "c"})
mapping = {frozen: "set as hashable key"}
other_frozen = frozenset(["c", "b", "a"])
print(f"Are keys equal? {frozen == other_frozen}")
print(f"Lookup with different order: {mapping[other_frozen]}")
print(f"Hash matches: {hash(frozen) == hash(other_frozen)}")
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…
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(…
How to Call a Parent Class __init__ with super() in Python
Shows how to chain __init__ calls through a class hierarchy using super(), so each class sets its own attributes while reusing the parent's initialization logic.
class Animal:
def __init__(self, name, species):
self.name = name
self.species = species
print(f"Animal init: {self.name}, {self.species}")
class Mammal(Animal):
def __init__(self, name, species, fur_color):
super().__init__(name, species)
self.fur_color = fur_color
…
How to Make a Python Class Hashable with __eq__ and __hash__
Define __eq__ and __hash__ together on a Python class so equal instances share the same hash and work correctly in sets and dictionary keys.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
if not isinstance(other, Point):
return NotImplemented
return self.x == other.x and self.y == other.y
def __hash__(self):
return hash((self.x, self.y))
def __repr…
How to Use __getstate__ and __setstate__ for Pickle in Python
Customize Python object serialization with the pickle __getstate__ and __setstate__ hooks to control exactly what data is stored and how it is restored.
import pickle
class Temperature:
def __init__(self, celsius):
self.celsius = celsius
def __getstate__(self):
"""Customize what gets pickled."""
state = self.__dict__.copy()
# Convert to Fahrenheit for storage (simulate transformation)
state['fahrenheit'] = (self.celsiu…
Filter List to Keep Only Whitelist Values in Python
Filter a list of values to keep only those present in a predefined whitelist set using a list comprehension.
def filter_whitelist(values, whitelist):
"""Return only values that are present in the whitelist set."""
return [value for value in values if value in whitelist]
if __name__ == "__main__":
raw_values = ["apple", "banana", "cherry", "date", "apple", "elderberry"]
allowed = {"apple", "banana", "date"}
…
Find Missing Numbers, Duplicates, and Ranges in Python
Analyze a list to identify missing numbers, duplicate values, and contiguous ranges using sets and the Counter class.
def find_missing_duplicates_ranges(numbers):
"""Find missing numbers, duplicates, and ranges in a list."""
from collections import Counter
if not numbers:
return {"missing": [], "duplicates": [], "ranges": []}
full_range = set(range(min(numbers), max(numbers) + 1))
present = set(n…
How to Compute Jaccard Similarity in Python
Compute the Jaccard similarity between two lists by converting them to sets and dividing the intersection size by the union size.
def jaccard_similarity(list1, list2):
set1 = set(list1)
set2 = set(list2)
intersection = set1 & set2
union = set1 | set2
if not union:
return 0.0
return len(intersection) / len(union)
if __name__ == "__main__":
a = [1, 2, 3, 4, 5]
b = [3, 4, 5, 6, 7]
pri…
How to Generate a Power Set in Python with Bitmasks
Generate the power set of a small list using a bitmask approach, producing all possible subsets.
def power_set(items):
"""Generate the power set of a list using bitmask approach."""
n = len(items)
result = []
for mask in range(1 << n):
subset = []
for i in range(n):
if mask & (1 << i):
subset.append(items[i])
result.append(subset)
r…
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.