Dictionaries & sets
Key–value maps, uniqueness, counting, grouping, and fast lookups.
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…
How to Filter a Dictionary by Predicate on Values in Python
This code defines a reusable function that builds a new dictionary containing only the items whose values satisfy a given predicate function.
def filter_dict_by_predicate(d, predicate):
"""Return a new dict with only items whose value passes the predicate."""
return {k: v for k, v in d.items() if predicate(v)}
if __name__ == "__main__":
scores = {"Alice": 85, "Bob": 42, "Charlie": 91, "Diana": 60}
# Keep only values greater than or equal t…
How to Filter a List of Dictionaries by Category in Python
Filter a list of dictionaries to include only records whose category is in an allowed set.
def filter_data(records, categories):
"""Return only records whose category is in the allowed set."""
allowed = set(categories)
filtered = []
for record in records:
if record["category"] in allowed:
filtered.append(record)
return filtered
if __name__ == "__main__":
data = …
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 …
Browse by section
Each section groups closely related Python snippets.
Dictionaries & sets — Python code examples
What you will find here
This page collects dictionaries & sets snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
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.