Dictionaries & sets
Key–value maps, uniqueness, counting, grouping, and fast lookups.
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.
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…
Convert Lists and Dictionaries to Sets in Python
Convert lists of pairs into dictionaries and lists or dictionaries into sets using simple helper functions.
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…
How to Count Co-occurrence Pairs in Python with Nested Dictionaries
This code counts how often any two items appear together in the same group, using a nested defaultdict keyed by item pairs.
from itertools import combinations
from collections import defaultdict
def count_cooccurrences(items_per_group):
cooccurrence = defaultdict(lambda: defaultdict(int))
for group in items_per_group:
for a, b in combinations(sorted(group), 2):
cooccurrence[a][b] += 1
cooccurrence[b…
How to Find Keys with Matching Values in Two Dictionaries in Python
Find dictionary keys where both dictionaries have the exact same value by iterating over key-value pairs and comparing them.
def find_matching_values(dict1, dict2):
"""Return list of keys that have the same value in both dicts."""
matches = []
for key, value in dict1.items():
if key in dict2 and dict2[key] == value:
matches.append(key)
return matches
if __name__ == "__main__":
# Example usage
di…
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.
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…
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.
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…
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.