Reference library

Dictionaries & sets

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

12 matches
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

Check Invertible Mapping for Duplicate Values in Python

Detect duplicate values among (key, value) pairs to ensure the mapping is invertible, using a dictionary for O(1) lookups.

dictionary mapping duplicate-check
Python
def invertible_after_dedup(pairs):
    """
    Check whether a set of (key, value) pairs is invertible,
    i.e., no duplicate values exist for different keys.
    """
    seen = {}
    for key, value in pairs:
        if value in seen and seen[value] != key:
            return False, f"Duplicate value '{value}' for k…
16 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 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…
13 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"…
13 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)
…
13 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…
11 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…
11 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 easy

How to Use MappingProxyType to Create Immutable Dict Views in Python

Create a read-only, immutable view of a dictionary using MappingProxyType from the types module, while the original dict stays mutable.

mappingproxytype dict immutable
Python
from types import MappingProxyType

config = {"debug": True, "port": 8080}

# Create an immutable read-only view of the dict
read_only_config = MappingProxyType(config)

print(f"Read-only value: {read_only_config['debug']}")
print(f"Dict is mapping: {isinstance(read_only_config, dict)}")

# Original dict can still be …
11 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)…
12 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…
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.