Dictionaries & sets
Key–value maps, uniqueness, counting, grouping, and fast lookups.
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 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.