Reference library

Dictionaries & sets

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

32 matches
Dictionaries & sets easy

Convert Lists and Dictionaries to Sets in Python

Convert lists of pairs into dictionaries and lists or dictionaries into sets using simple helper functions.

dict set conversion
Python
def convert_to_dict(data):
    """Convert list of tuples or lists into a dictionary."""
    return dict(data)


def convert_to_set(data):
    """Convert list or dictionary into a set of its keys/values."""
    if isinstance(data, dict):
        return set(data.keys())
    return set(data)


def convert_collection(data…
14 0 Open
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

Group Data by Key in Python with Dictionaries and Sets

Group items into a dictionary of sets using a key function, a beginner-friendly pattern for organizing data by categories.

grouping dictionaries sets
Python
def group_data(items, key_func):
    """Group items into a dictionary of sets based on a key function."""
    grouped = {}
    for item in items:
        key = key_func(item)
        if key not in grouped:
            grouped[key] = set()
        grouped[key].add(item)
    return grouped


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

How to Aggregate Order Data with Sets and Dictionaries in Python

Combine sets and dictionaries to find unique products and total quantities from a list of orders in Python.

sets dictionaries data aggregation
Python
def find_unique_products(orders):
    """Return set of all products ordered across multiple orders."""
    all_products = set()
    for order in orders:
        all_products.update(order.get("items", []))
    return all_products


def product_summary(orders):
    """Build a dictionary mapping each product to its total…
13 0 Open
Dictionaries & sets easy

How to Build a Gradebook with Python Dictionaries and Sets

Create a gradebook dictionary from student names and grades, find top students with a set comprehension, and add extra credit with a dict comprehension.

dictionaries sets comprehensions
Python
def build_gradebook(students, grades):
    """Create a dictionary mapping student names to their grades."""
    return dict(zip(students, grades))


def find_top_students(gradebook, passing_grade=60):
    """Return a set of students with grades at or above the passing grade."""
    return {name for name, grade in grad…
12 0 Open
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 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 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 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 Find Symmetric Difference Between Two Python Sets

Compute elements unique to each set and build a flag dictionary showing membership across two Python sets.

sets set-operations symmetric-difference
Python
def symmetric_difference_with_flags(set_a, set_b):
    """Return elements in either set but not both, grouped by which set they came from."""
    only_in_a = set_a - set_b
    only_in_b = set_b - set_a
    
    print(f"Only in A: {only_in_a}")
    print(f"Only in B: {only_in_b}")
    print(f"Symmetric difference: {onl…
13 0 Open
Dictionaries & sets easy

How to Find the Intersection of Permission Sets in Python

This code defines a function that takes a list of permission sets and returns a set containing only the permissions common to all sets, with a short-circuit for empty results.

sets intersection permissions
Python
from typing import Set

def intersect_permissions(permission_sets: list[Set[str]]) -> Set[str]:
    """
    Given a list of permission sets, return the common permissions
    present in every set.
    """
    if not permission_sets:
        return set()
    
    common = permission_sets[0]
    for perm_set in permissi…
12 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 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 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 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 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.

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.