Dictionaries & sets
Key–value maps, uniqueness, counting, grouping, and fast lookups.
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…
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():
…
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 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 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…
How to Count Words and Find Common Words in Python with Dictionaries and Sets
Build a simple text processor that counts unique words with dictionaries and finds common words across text halves using sets.
def process_text(text):
"""Process text: count unique words with counts, find common words."""
words = text.lower().replace(",", "").replace(".", "").split()
word_counts = {}
for word in words:
word_counts[word] = word_counts.get(word, 0) + 1
total_words = len(words)
unique_wo…
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.
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…
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.
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…
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.
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…
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.
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…
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.
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__ == "__…
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.
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…
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.
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…
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.
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"…
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…
How to Validate Text and Count Words in Python
Count word frequencies, find unique and repeated words in a text using Python dictionaries and sets for beginner text validation.
def validate_text(text):
words = text.lower().split()
word_counts = {}
for word in words:
cleaned = word.strip('.,!?;:"\'')
if cleaned:
word_counts[cleaned] = word_counts.get(cleaned, 0) + 1
unique_words = set(word_counts.keys())
repeated_words = {word for word…
How to count words and find unique words in Python
Build a beginner-friendly text processor that counts word frequencies, finds unique words, and identifies words with vowels using dictionaries and sets.
def text_processor(text):
words = text.lower().replace(",", "").replace(".", "").split()
word_count = {}
for word in words:
word_count[word] = word_count.get(word, 0) + 1
unique_words = set(words)
vowels = set("aeiou")
words_with_vowels = {word for word in unique_words if vowe…
How to swap dict keys and values in Python when values are unique
Swap dict keys and values using a dict comprehension, with a guard that raises an error when values repeat.
def swap_dict_keys_values(d):
"""Swap keys and values in a dict, assuming values are unique."""
if len(set(d.values())) != len(d.values()):
raise ValueError("Values must be unique to swap keys and values")
return {v: k for k, v in d.items()}
if __name__ == "__main__":
original = {"a": 1, "b": …
Text Processor with Dictionaries and Sets in Python
Build a simple text processor that counts word frequencies with a dictionary and tracks unique words with a set.
def analyze_text(text):
words = text.lower().split()
word_freq = {}
unique_words = set()
for word in words:
clean_word = word.strip('.,!?;:')
if clean_word:
word_freq[clean_word] = word_freq.get(clean_word, 0) + 1
unique_words.add(clean_word)
return…
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.