Reference library

Python Code Samples

Easy snippets you can copy, study, and run in the browser editor.

92 matches
Dictionaries & sets easy

How to Check Data Type and Inspect Dictionaries and Sets in Python

Inspect dictionaries and sets by printing their contents, types, and sizes using a small helper function.

dictionaries sets isinstance
Python
def check_data(data):
    """Helper to inspect dictionaries and sets."""
    if isinstance(data, dict):
        print(f"Dictionary with {len(data)} keys")
        for key, value in data.items():
            print(f"  {key}: {value} ({type(value).__name__})")
    elif isinstance(data, set):
        print(f"Set with {le…
13 0 Open
Dictionaries & sets easy

How to Compute Set Union of Tags from Multiple Items in Python

Collect all unique tags from a list of dictionaries using set union with update() in Python.

set union tags dictionaries
Python
items = [
    {"id": 1, "tags": {"python", "web"}},
    {"id": 2, "tags": {"web", "api", "sql"}},
    {"id": 3, "tags": {"python", "data"}},
]


def get_union_of_tags(item_list):
    all_tags = set()
    for item in item_list:
        all_tags.update(item["tags"])
    return all_tags


if __name__ == "__main__":
    u…
14 0 Open
Dictionaries & sets easy

How to Count Co-occurrence Pairs in Python with Nested Dictionaries

This code counts how often any two items appear together in the same group, using a nested defaultdict keyed by item pairs.

dictionaries co-occurrence counter
Python
from itertools import combinations
from collections import defaultdict

def count_cooccurrences(items_per_group):
    cooccurrence = defaultdict(lambda: defaultdict(int))
    for group in items_per_group:
        for a, b in combinations(sorted(group), 2):
            cooccurrence[a][b] += 1
            cooccurrence[b…
12 0 Open
Dictionaries & sets easy

How to Count Elements and Find Duplicates in a Python List

Count occurrences of each element in a list, extract unique values, and identify duplicates using Python dictionaries and sets.

dictionary set counting
Python
def analyze_counts(data):
    """Count elements, return unique values, and find duplicates."""
    
    # Count occurrences using a dictionary
    counts = {}
    for item in data:
        counts[item] = counts.get(item, 0) + 1
    
    # Alternative compact approach with set
    unique_items = set(data)
    
    # Fi…
12 0 Open
Dictionaries & sets easy

How to Count Tags with Sets and Dictionaries in Python

Count tag frequencies and collect unique tags from a list of dictionaries using Counter and sets in Python.

collections counter sets
Python
from collections import Counter
import json


def count_tags(entries):
    """Count tag frequencies across a list of entry dicts, using sets/dicts."""
    tag_counter = Counter()
    all_tags = set()
    for entry in entries:
        tags = set(entry["tags"])
        all_tags.update(tags)
        tag_counter.update(ta…
11 0 Open
Dictionaries & sets easy

How to Count Word Frequencies in Python

Count how often each word appears in a string and list the unique words using Python dictionaries and sets.

dictionaries sets text-processing
Python
def text_processor(text):
    words = text.lower().split()
    word_count = {}
    for word in words:
        word_count[word] = word_count.get(word, 0) + 1
    unique_words = set(words)
    return word_count, unique_words

if __name__ == "__main__":
    sample_text = "The quick brown fox jumps over the lazy dog and t…
14 0 Open
Dictionaries & sets easy

How to Count Words and Find Common Words in Python with Dictionaries and Sets

Build a simple text processor that counts unique words with dictionaries and finds common words across text halves using sets.

dictionaries sets word-count
Python
def process_text(text):
    """Process text: count unique words with counts, find common words."""
    words = text.lower().replace(",", "").replace(".", "").split()
    
    word_counts = {}
    for word in words:
        word_counts[word] = word_counts.get(word, 0) + 1
    
    total_words = len(words)
    unique_wo…
13 0 Open
Dictionaries & sets easy

How to Diff Two Dicts in Python: Added, Removed, and Changed Keys

Compare two dictionaries and report added, removed, and changed keys using Python's set operations on dict keys.

dict diff set-operations
Python
def diff_dicts(old: dict, new: dict) -> dict:
    """Compare two dicts and report added, removed, and changed keys."""
    added = {k: new[k] for k in new.keys() - old.keys()}
    removed = {k: old[k] for k in old.keys() - new.keys()}

    common_keys = old.keys() & new.keys()
    changed = {k: (old[k], new[k]) for k …
15 0 Open
Dictionaries & sets easy

How to Extract Data by Category in Python with Dictionaries and Sets

Use set comprehensions and a defaultdict to extract product names by category and compute total prices per category from a list of dictionaries.

dictionaries sets comprehensions
Python
from collections import defaultdict

# Sample data: products with categories and prices
product_data = [
    {"name": "Apple", "category": "fruit", "price": 0.50},
    {"name": "Banana", "category": "fruit", "price": 0.30},
    {"name": "Carrot", "category": "vegetable", "price": 0.80},
    {"name": "Bread", "category…
12 0 Open
Dictionaries & sets easy

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.

dictionary set filter
Python
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 = …
12 0 Open
Dictionaries & sets easy

How to Find Keys with Matching Values in Two Dictionaries in Python

Find dictionary keys where both dictionaries have the exact same value by iterating over key-value pairs and comparing them.

dictionaries comparison data-matching
Python
def find_matching_values(dict1, dict2):
    """Return list of keys that have the same value in both dicts."""
    matches = []
    for key, value in dict1.items():
        if key in dict2 and dict2[key] == value:
            matches.append(key)
    return matches


if __name__ == "__main__":
    # Example usage
    di…
13 0 Open
Dictionaries & sets easy

How to Group a List of Dictionaries by Key in Python

Group a list of dictionaries by a specified key field using dict.setdefault to build a dictionary of lists.

dictionaries grouping setdefault
Python
def group_by_key(records, key):
    grouped = {}
    for record in records:
        grouped.setdefault(record[key], []).append(record)
    return grouped

if __name__ == "__main__":
    data = [
        {"name": "Alice", "dept": "engineering"},
        {"name": "Bob", "dept": "sales"},
        {"name": "Carol", "dept"…
14 0 Open
Dictionaries & sets easy

How to Index a List of Records by Unique ID in Python

Build a dictionary that maps each record's unique id to the record itself from a list of dictionaries.

dictionary index records
Python
from typing import List, Dict, Any

def index_by_id(records: List[Dict[str, Any]], id_field: str = "id") -> Dict[Any, Dict[str, Any]]:
    """Build a dictionary mapping each record's unique id to the record itself."""
    return {record[id_field]: record for record in records}

if __name__ == "__main__":
    sample_re…
15 0 Open
Dictionaries & sets easy

How to Map Dictionary Values with a Transformation Function in Python

Create a reusable function that applies a transformation to every value in a dictionary and returns a new dict.

dictionaries mapping comprehension
Python
def transform_dict_values(d, func):
    """Apply a transformation function to every value in a dictionary."""
    return {key: func(value) for key, value in d.items()}


if __name__ == "__main__":
    original = {"a": 1, "b": 2, "c": 3}
    doubled = transform_dict_values(original, lambda x: x * 2)
    print(doubled)
…
14 0 Open
Dictionaries & sets easy

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.

dictionaries sets merge
Python
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…
14 0 Open
Dictionaries & sets easy

How to Merge Two Dictionaries in Python with the Spread Operator

Merge two Python dictionaries into one new dict using the ** unpacking (spread) operator, with later keys overriding earlier ones.

dicts merge spread-operator
Python
def merge_two_dicts(dict1: dict, dict2: dict) -> dict:
    """Merge two dictionaries using the spread operator pattern."""
    # The ** operator unpacks key-value pairs, later keys overwrite earlier ones
    merged = {**dict1, **dict2}
    return merged


if __name__ == "__main__":
    # Example usage with overlapping…
15 0 Open
Dictionaries & sets easy

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.

dictionaries sets data-cleaning
Python
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…
12 0 Open
Dictionaries & sets easy

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.

dictionaries sets data-cleaning
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__ == "__…
14 0 Open
Dictionaries & sets easy

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.

dictionary set defaultdict
Python
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…
12 0 Open
Dictionaries & sets easy

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.

sorting dictionaries sets
Python
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…
12 0 Open
Dictionaries & sets easy

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.

collections counter bags
Python
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…
14 0 Open
Dictionaries & sets easy

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.

dictionaries sets data-normalization
Python
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"…
13 0 Open
Dictionaries & sets easy

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.

chainmap configuration collections
Python
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…
14 0 Open
Dictionaries & sets easy

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.

dictionary set beginner
Python
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…
11 0 Open

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

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. 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.