Reference library

Dictionaries & sets

Key–value maps, uniqueness, counting, grouping, and fast lookups.

3 matches
Dictionaries & sets easy

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.

dict-comprehension filtering dictionaries
Python
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…
13 0 Open
Dictionaries & sets easy

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.

dictionary filtering lambda
Python
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…
14 0 Open
Dictionaries & sets easy

How to Remove Banned Words from a Set in Python

Filter a vocabulary set by removing banned words using the .difference() method.

sets set difference filtering
Python
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 …
16 0 Open

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.