How to merge dictionaries and sets in Python
Merges multiple dictionaries with the ** unpacking operator and combines sets using union operations into a single structure.
Python code
42 linesdef merge_dictionaries_and_sets(school_dict, teacher_dict, course_dict, student_sets):
"""
Merges multiple dictionaries and sets into a single combined structure.
Demonstrates dict unpacking and set union operations.
"""
# Merge all dictionaries using the unpacking operator (Python 3.9+)
merged_schedule = {
**school_dict,
**teacher_dict,
**course_dict
}
# Merge all sets using the union operator (Python 3.9+)
merged_students = set()
for student_set in student_sets:
merged_students |= student_set
return merged_schedule, merged_students
if __name__ == "__main__":
# Sample data: school, teacher, and course information
school_info = {"name": "Green Valley High", "founded": 1965, "principal": "Dr. Smith"}
teacher_info = {"math": "Mrs. Jones", "science": "Mr. Chen", "name": "Staff Directory"}
course_info = {"algebra": "Math 101", "biology": "Life Science"}
# Sample student sets from different grade levels
freshmen = {"Alice", "Bob", "Charlie"}
sophomores = {"Charlie", "David", "Emma"}
juniors = {"Emma", "Frank", "Grace"}
combined_info, all_students = merge_dictionaries_and_sets(
school_info, teacher_info, course_info,
[freshmen, sophomores, juniors]
)
print("Combined schedule:")
for key, value in combined_info.items():
print(f" {key}: {value}")
print(f"\nAll unique students ({len(all_students)} total):")
print(" " + ", ".join(sorted(all_students)))
Output
Combined schedule:
name: Staff Directory
founded: 1965
principal: Dr. Smith
math: Mrs. Jones
science: Mr. Chen
algebra: Math 101
biology: Life Science
All unique students (6 total):
Alice, Bob, Charlie, David, Emma, Frank, Grace
How it works
The ** unpacking operator merges dictionaries by inserting key-value pairs from left to right, so later dictionaries override earlier ones with the same key — that's why name becomes "Staff Directory" from teacher_info. The |= operator performs an in-place set union, adding all unique elements from each set into merged_students. This avoids duplicates automatically since sets only store unique values. The function returns a tuple containing the combined dictionary and set, which Python unpacks into two variables at the call site. Sorting the final set in the print statement gives deterministic, readable output.
Common mistakes
- Forgetting that later dict keys overwrite earlier ones during unpacking
- Using `student_set | merged_students` instead of `merged_students |= student_set` (same result but less efficient)
- Assuming set order is preserved when printing without sorted()
- Passing a set instead of a list of sets to the function
Variations
- Use `merged = {**a, **b, **c}` or `merged = a | b | c` (Python 3.9+) for quick one-line merges
- Use `merged_students = set().union(*student_sets)` to combine all sets in one call
Real-world use cases
- Consolidating configuration dictionaries from multiple services into one settings object at app startup.
- Aggregating user IDs from several access groups into a single deduplicated roster for permission checks.
- Combining class rosters scraped from different sources into one master student list for a school database.
Sponsored
More from Dictionaries & sets
- Build a Case-Insensitive Dict with a Wrapper Class in Python medium
- Build a defaultdict histogram of categories in Python easy
- Build adjacency dict graph from edges in Python easy
- Build an OrderedDict insertion order demo in Python 3 easy
- Check Invertible Mapping for Duplicate Values in Python easy
- Compare Two Dictionaries in Python easy
Keep learning
Related tutorials and quizzes for this topic.