Reference library

Dictionaries & sets

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

63 matches
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 Group Data by Category in Python with a Split Data Helper

This code groups a list of (category, item) pairs into a dictionary where each key is a category and each value is a list of items belonging to that category.

dictionary grouping iterable
Python
def split_data(categories):
    """
    Group data items into buckets based on a key function.
    Returns a dict where keys are bucket names and values are lists of items.
    """
    buckets = {}
    for category, item in categories:
        if category not in buckets:
            buckets[category] = []
        buck…
14 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 medium

How to Implement Disjoint Set Union Find in Python

Implement a Disjoint Set Union-Find data structure using a Python dictionary for parent tracking, with path compression and connectivity checks.

disjoint-set union-find graph
Python
class DisjointSet:
    def __init__(self):
        self.parent = {}

    def find(self, x):
        # Path compression
        if self.parent[x] != x:
            self.parent[x] = self.find(self.parent[x])
        return self.parent[x]

    def union(self, x, y):
        # Initialize if not present
        if x not in…
13 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 Invert a Dictionary in Python Safely

Swap dictionary keys and values while detecting duplicate values to prevent silent data loss.

dictionary inversion data-safety
Python
def invert_dict_safely(d):
    inverted = {}
    for key, value in d.items():
        if value not in inverted:
            inverted[value] = key
        else:
            raise ValueError(f"Duplicate value '{value}' would cause data loss")
    return inverted


if __name__ == "__main__":
    sample = {"a": 1, "b": 2,…
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 Parse Query String to Dict with Duplicate Keys in Python

Convert a URL query string into a Python dictionary, merging duplicate keys into lists while keeping single values as scalars.

query-string dict url-parsing
Python
from urllib.parse import parse_qs


def parse_query_to_dict(query_string):
    parsed = parse_qs(query_string, keep_blank_values=True)
    return {key: values if len(values) > 1 else values[0] for key, values in parsed.items()}


if __name__ == "__main__":
    query = "name=John&name=Jane&age=30&city=&city=Paris&empty…
13 0 Open
Dictionaries & sets easy

How to Pickle a Python Dict and Load It Back

Save a dictionary to a binary file with pickle.dump() and reload it with pickle.load(), showing the round trip and type preservation.

pickle serialization dict
Python
import pickle

data = {"name": "Alice", "scores": [87, 92, 95], "active": True}

print("Original dict:", data)

with open("safe_demo.pkl", "wb") as f:
    pickle.dump(data, f)

with open("safe_demo.pkl", "rb") as f:
    loaded = pickle.load(f)

print("Loaded dict:", loaded)
print("Type:", type(loaded).__name__)
print(…
15 0 Open
Dictionaries & sets medium

How to Recursively Remove None Values from Nested Dictionaries in Python

Recursively removes all None values from nested dictionaries and lists while preserving non-None data.

dictionaries recursion data-cleaning
Python
def prune_none(obj):
    if isinstance(obj, dict):
        return {
            k: prune_none(v)
            for k, v in obj.items()
            if v is not None and prune_none(v) is not None
        }
    elif isinstance(obj, list):
        pruned = [prune_none(item) for item in obj]
        pruned = [item for item i…
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 Serialize a Dictionary to a Query String in Python

Convert a Python dictionary into a URL-encoded query string using the standard library's urllib.parse.urlencode function.

urllib query-string urlencode
Python
import urllib.parse

def dict_to_query_string(params):
    """Serialize a dictionary to a URL query string."""
    return urllib.parse.urlencode(params)

if __name__ == "__main__":
    data = {
        "name": "Alice Johnson",
        "age": 30,
        "city": "New York",
        "interests": ["coding", "hiking"]
   …
13 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 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 Sort a Python Dictionary by Value Descending

Sort dictionary items by their values in descending order and return a new dictionary.

dictionary sorting values
Python
def sort_dict_by_value_desc(d):
    return dict(sorted(d.items(), key=lambda item: item[1], reverse=True))


if __name__ == "__main__":
    sample = {"apple": 5, "banana": 2, "cherry": 8, "date": 8}
    result = sort_dict_by_value_desc(sample)
    print(result)
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

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.