Dictionaries & sets
Key–value maps, uniqueness, counting, grouping, and fast lookups.
Build a defaultdict histogram of categories in Python
Count occurrences of each category in a list using collections.defaultdict(int) for automatic initialization.
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", …
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.
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)…
Build an OrderedDict insertion order demo in Python 3
Demonstrate how OrderedDict preserves insertion order, how updates keep position, and how re-insertion moves keys to the end.
from collections import OrderedDict
def demo_ordered_dict():
# Create an OrderedDict and insert items in a specific order
ordered = OrderedDict()
ordered['banana'] = 3
ordered['apple'] = 2
ordered['cherry'] = 5
ordered['date'] = 1
print("Insertion order preserved:")
for key, value in …
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…
Compare Two Dictionaries in Python
Compare two dictionaries by finding common keys, unique keys, and value differences using Python's set operations.
def compare_data(dict1, dict2):
"""Compare two dictionaries and summarize similarities/differences."""
keys1 = set(dict1.keys())
keys2 = set(dict2.keys())
common_keys = keys1 & keys2
only_in_first = keys1 - keys2
only_in_second = keys2 - keys1
print(f"Common keys ({len(common_keys…
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…
Convert namedtuple to dict with asdict in Python
Convert a namedtuple instance into an ordinary dictionary using the asdict function from the collections module's namedtuple utility.
from collections import namedtuple, asdict
def main():
# Define a namedtuple for a person
Person = namedtuple("Person", ["name", "age", "city"])
person = Person(name="Alice", age=30, city="New York")
# Convert namedtuple to dict
person_dict = asdict(person)
print("Original namedtuple…
Count Word Frequency in Python with dict
Count how often each word appears in a text using Python's collections.Counter and regular expressions.
from collections import Counter
import re
def count_word_frequency(text):
"""Count frequency of each word in text (case-insensitive)."""
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 …
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.
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():
…
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.
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(…
Filter Dictionary Keys by Prefix in Python
Use a dict comprehension to build a new dictionary containing only keys that start with a given prefix.
def filter_dict_keys(data, prefix="temp_"):
"""
Filter a dictionary by keeping only keys that start with a given prefix.
Uses a dict comprehension to build a new dictionary.
"""
if not isinstance(data, dict):
raise ValueError("data must be a dictionary")
return {key: value for key, valu…
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.
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
…
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.
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__":
…
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.
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…
How to Build a Gradebook with Python Dictionaries and Sets
Create a gradebook dictionary from student names and grades, find top students with a set comprehension, and add extra credit with a dict comprehension.
def build_gradebook(students, grades):
"""Create a dictionary mapping student names to their grades."""
return dict(zip(students, grades))
def find_top_students(gradebook, passing_grade=60):
"""Return a set of students with grades at or above the passing grade."""
return {name for name, grade in grad…
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.
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…
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.
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…
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.
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…
How to Convert a Counter to a Plain Dict with Sorted Items in Python
This code converts a collections.Counter into a regular dictionary with items sorted by key, useful for stable, readable output.
from collections import Counter
def counter_to_sorted_dict(counter):
"""Convert a Counter to a plain dict with sorted items."""
return dict(sorted(counter.items()))
if __name__ == "__main__":
# Example usage
data = Counter(['apple', 'banana', 'apple', 'cherry', 'banana', 'date', 'apple'])
print("…
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 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.
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…
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.
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…
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.
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…
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.
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…
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.