Reference library

Dictionaries & sets

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

31 matches
Dictionaries & sets easy

Build a defaultdict histogram of categories in Python

Count occurrences of each category in a list using collections.defaultdict(int) for automatic initialization.

defaultdict histogram collections
Python
from collections import defaultdict

def build_category_histogram(items):
    """Count occurrences of each category in a list of items."""
    histogram = defaultdict(int)
    for item in items:
        histogram[item] += 1
    return dict(histogram)

if __name__ == "__main__":
    categories = ["fruit", "vegetable", …
10 0 Open
Dictionaries & sets easy

Build adjacency dict graph from edges in Python

Convert a list of edges into an undirected adjacency dictionary, mapping each node to its neighbors, with sorted output.

graph adjacency dictionary
Python
def build_adjacency_dict(edges):
    graph = {}
    for u, v in edges:
        if u not in graph:
            graph[u] = []
        if v not in graph:
            graph[v] = []
        graph[u].append(v)
        graph[v].append(u)
    return graph

if __name__ == "__main__":
    edges = [(1, 2), (2, 3), (3, 4), (4, 1)…
12 0 Open
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 medium

Find All Leaf Paths in a Nested Dict in Python

Recursively traverse a nested dictionary and yield every leaf path as a list of keys, including paths to empty dictionaries.

dictionary recursion nested-data
Python
def find_leaf_paths(data, path=None):
    if path is None:
        path = []
    
    if not isinstance(data, dict) or not data:
        yield path
        return
    
    for key, value in data.items():
        yield from find_leaf_paths(value, path + [key])

if __name__ == "__main__":
    nested = {
        "a": 1,
…
13 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 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 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 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 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 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 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 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…
12 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 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 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.