How to Use Dictionaries and Sets in Python for Beginners
Demonstrates Python dictionary operations and set operations with examples, including access, modification, defaults, and set algebra.
Python code
38 linesdef demonstrate_collections():
# Dictionary basics
student = {
"name": "Alice",
"age": 20,
"courses": ["Math", "Physics"]
}
print("Dictionary:", student)
# Access and modify
student["age"] = 21
student["grade"] = "A"
print("Modified:", student)
# Get with default
print("Major:", student.get("major", "Undecided"))
# Set basics
courses_taken = {"Math", "Physics", "Chemistry"}
courses_planned = {"Math", "Biology", "Art"}
# Set operations
print("Union:", courses_taken | courses_planned)
print("Intersection:", courses_taken & courses_planned)
print("Difference:", courses_taken - courses_planned)
# Dictionary from two lists
names = ["Bob", "Carol", "Dave"]
ages = [25, 30, 35]
people = dict(zip(names, ages))
print("Zipped dict:", people)
# Set of dictionary keys
keys = set(student.keys())
print("Keys as set:", keys)
if __name__ == "__main__":
demonstrate_collections()
Output
Dictionary: {'name': 'Alice', 'age': 20, 'courses': ['Math', 'Physics']}
Modified: {'name': 'Alice', 'age': 21, 'courses': ['Math', 'Physics'], 'grade': 'A'}
Major: Undecided
Union: {'Art', 'Biology', 'Chemistry', 'Math', 'Physics'}
Intersection: {'Math'}
Difference: {'Physics', 'Chemistry'}
Zipped dict: {'Bob': 25, 'Carol': 30, 'Dave': 35}
Keys as set: {'name', 'age', 'courses', 'grade'}
How it works
This script defines a function that prints dictionary operations like updating values and adding keys, and demonstrates the get() method for safe access with a default. It then shows set operations using union (|), intersection (&), and difference (-). The zip() function pairs two lists into tuples, and dict() converts them into a dictionary. The set() constructor converts dictionary keys into a set, which is a common pattern for key lookups. The script runs when executed directly because of the if __name__ == "__main__" guard.
Common mistakes
- Using `student['major']` without checking existence leads to KeyError; use `.get()`.
- Forgetting that sets are unordered, so output order of set elements can vary.
- Assuming `dict(zip(...))` preserves order — it does, but keys must be unique.
- Adding to a set with `add()` vs. a dictionary with assignment; mixing them up.
Variations
- Use `defaultdict` from collections for automatic default values.
- Use `setdefault()` to set a key only if it doesn't exist.
- Use `|=` to update a set in-place with union.
Real-world use cases
- Storing user profile data where fields are added or updated on the fly.
- Finding common elements between lists, like shared tags between blog posts.
- Pairing employee names with their IDs when loading data from two separate arrays.
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.