Reference library

Dictionaries & sets

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

12 matches
Dictionaries & sets easy

Count Words in Python with Dictionaries and Sets

Text analysis example that counts total words, finds unique words with a set, and tallies character frequencies with a dictionary.

dictionaries sets text-processing
Python
def analyze_text(text: str) -> dict:
    """Count words, find unique words, and show common characters."""
    words = text.lower().split()
    word_count = len(words)
    unique_words = set(words)
    char_counts = {}
    
    for word in words:
        for char in word:
            if char.isalpha():
               …
13 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 Word Frequencies in Python with Counter and Sets

This code processes a text string by lowercasing, splitting into words, counting frequencies with Counter, and extracting unique and sorted word lists using sets.

counter sets text-processing
Python
from collections import Counter

def process_text(text):
    words = text.lower().split()
    word_counts = Counter(words)
    unique_words = set(words)
    sorted_words = sorted(unique_words)
    
    return {
        "total_words": len(words),
        "unique_words": len(unique_words),
        "word_frequencies": di…
12 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 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 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 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
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 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.

defaultdict grouping dictionaries
Python
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)…
13 0 Open
Dictionaries & sets easy

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.

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

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.

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

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.

dictionary set word-count
Python
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…
12 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.