Reference library

Dictionaries & sets

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

16 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

Count word frequency in Python with dict and Counter

Count how often each word appears in a string using Counter, converted to a plain dict, and print results alphabetically.

counter dictionary word-frequency
Python
from collections import Counter
import re

def count_word_frequency(text):
    words = re.findall(r'\b\w+\b', text.lower())
    return dict(Counter(words))

if __name__ == "__main__":
    sample_text = "The quick brown fox jumps over the lazy dog. The dog barks, and the fox runs."
    frequency = count_word_frequency(…
12 0 Open
Dictionaries & sets easy

Flatten a Nested Dict to Dot Notation Keys in Python

Recursively flatten a nested dictionary into a flat dictionary with dot-separated keys using a small recursive function.

dict flatten recursion
Python
def flatten_dict(nested, parent_key='', sep='.'):
    items = {}
    for key, value in nested.items():
        new_key = f"{parent_key}{sep}{key}" if parent_key else key
        if isinstance(value, dict):
            items.update(flatten_dict(value, new_key, sep))
        else:
            items[new_key] = value
    …
11 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 Check if a Set is a Subset in Python

Check whether one set contains all elements of another set using the issubset method.

set subset membership
Python
def is_subset(allowed_set, check_set):
    """
    Check if check_set is a subset of allowed_set.
    Returns True if all elements of check_set are in allowed_set, otherwise False.
    """
    return check_set.issubset(allowed_set)

if __name__ == "__main__":
    # Example usage
    allowed = {1, 2, 3, 4, 5}
    valid…
17 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 Create a Dict from Two Parallel Lists in Python (zip)

Build a dictionary by pairing elements from two parallel lists using Python's built-in zip function and dict constructor.

dictionary zip lists
Python
keys = ["name", "age", "city"]
values = ["Alice", 30, "New York"]

result = dict(zip(keys, values))
print(result)
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 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 Set Nested Dict Value Creating Missing Keys in Python

Set a value deep inside a nested dictionary, automatically creating any missing intermediate dicts along the path.

dictionary nested mutation
Python
def set_nested_value(d, keys, value):
    """
    Set a value in a nested dict, creating missing intermediate keys.
    
    Args:
        d: The dict to modify
        keys: Iterable of keys forming the path (e.g., ['a', 'b', 'c'])
        value: The value to set at the final key
    """
    current = d
    for key i…
13 0 Open
Dictionaries & sets easy

How to Sort Dictionary Keys Alphabetically in Python

This code returns a list of dictionary keys sorted alphabetically, using a case-insensitive comparison while preserving the original insertion order for keys that are equal.

sorting dictionary case-insensitive
Python
data = {
    "banana": 3,
    "apple": 1,
    "Cherry": 5,
    "date": 2,
    "apple": 4,
    "Fig": 6,
    "banana": 2,
}

def sort_dict_keys_alphabetically(d):
    """Return a list of keys sorted alphabetically (case-insensitive), stable for duplicates."""
    return sorted(d.keys(), key=lambda k: k.lower())

if __n…
11 0 Open
Dictionaries & sets easy

How to Use defaultdict(set) in Python to Group Unique Values

Group key-value pairs into a dictionary of sets, automatically creating a new set for each key using defaultdict.

defaultdict sets dictionaries
Python
from collections import defaultdict

def track_groups(pairs):
    groups = defaultdict(set)
    for key, value in pairs:
        groups[key].add(value)
    return groups

if __name__ == "__main__":
    data = [
        ("fruit", "apple"),
        ("fruit", "banana"),
        ("fruit", "apple"),
        ("veg", "carrot…
15 0 Open
Dictionaries & sets easy

How to Validate Required Dict Keys in Python

Check whether a dictionary contains all required keys and return the list of missing ones using a simple list comprehension.

dictionary validation missing-keys
Python
def find_missing_keys(data: dict, required_keys: list) -> list:
    """Return a list of required keys that are missing from the dictionary."""
    return [key for key in required_keys if key not in data]


if __name__ == "__main__":
    user_data = {
        "name": "Alice",
        "email": "alice@example.com",
     …
12 0 Open
Dictionaries & sets easy

Parse Env Vars into Typed Dict in Python

Convert a list of environment variable names into a dictionary with automatically detected types (bool, int, float, or string), defaulting missing vars to None.

env-vars type-conversion dict
Python
import os
from typing import Any, Dict


def parse_env_vars(env_names: list[str], env: Dict[str, str] | None = None) -> Dict[str, Any]:
    """Parse a list of environment variable names into a typed dict.

    Each variable is parsed as:
    - bool: "true"/"false" (case-insensitive)
    - int: if it can be converted t…
13 0 Open
Dictionaries & sets easy

Validate dictionary data with sets in Python

Validate a dictionary against required keys and allowed value sets, returning a list of validation errors.

dictionaries sets validation
Python
def validate_data(data, required_keys, allowed_values=None):
    """
    Validate a dictionary against required keys and optional allowed value sets.
    Returns a list of validation errors (empty list if valid).
    """
    errors = []
    
    # Check for missing required keys
    missing = set(required_keys) - set(…
14 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.