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.

Easy Python 3.9+ Aug 9, 2026 Dictionaries & sets 11 views 0 copies

Python code

38 lines
Python 3.9+
def 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

stdout
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

  1. Use `defaultdict` from collections for automatic default values.
  2. Use `setdefault()` to set a key only if it doesn't exist.
  3. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Dictionaries & sets

Related tutorials and quizzes for this topic.