Previous | Tutorial index | Next

Tutorial 5: Working with Sets and Dictionaries

Learning Objectives

Overview

Sets and dictionaries are two essential non‑sequence data structures in Python. They are both unordered, mutable collections (with some caveats), but they serve very different purposes:

This tutorial dives deep into both, covering their creation, methods, operations, and best practices.

1. Sets – Unordered Collections of Unique Elements

1.1 Definition and Creation

A set is an unordered, mutable collection of distinct, hashable objects. Because it is unordered, sets do not support indexing, slicing, or any sequence operations.

fruits = {"apple", "banana", "cherry"}
empty_set = set()
numbers = set([1, 2, 2, 3]) # {1, 2, 3} – duplicates removed letters = set("hello") # {'h', 'e', 'l', 'o'} (order arbitrary)

1.2 Properties of Sets

1.3 Adding and Removing Elements

s = {1, 2, 3} s.add(4) # {1, 2, 3, 4} s.add(2) # {1, 2, 3, 4} (unchanged) s.remove(3) # {1, 2, 4} s.discard(5) # no effect popped = s.pop() # removes an arbitrary element (say 1) s.clear() # set()

1.4 Set Operations – Mathematical Power

Sets support all standard mathematical set operations. You can use both methods and operators:

Operation Method Operator Description
Union set1.union(set2, ...) set1 | set2 All elements from both sets
Intersection set1.intersection(set2, ...) set1 & set2 Common elements
Difference set1.difference(set2, ...) set1 - set2 Elements in set1 but not in set2
Symmetric Difference set1.symmetric_difference(set2) set1 ^ set2 Elements in exactly one of the sets
Subset / Superset set1.issubset(set2), set1.issuperset(set2) <=, >= Check inclusion
Disjoint set1.isdisjoint(set2) No common elements
A = {1, 2, 3, 4} B = {3, 4, 5, 6} print(A | B) # {1, 2, 3, 4, 5, 6} print(A & B) # {3, 4} print(A - B) # {1, 2} print(A ^ B) # {1, 2, 5, 6} print(A.issubset(B)) # False

In‑place updates: Methods like update(), intersection_update(), difference_update(), and symmetric_difference_update() modify the set in place.

1.5 Set Comprehensions

Like lists, sets support comprehensions:

squares = {x**2 for x in range(5)} # {0, 1, 4, 9, 16} even = {x for x in range(10) if x % 2 == 0} # {0, 2, 4, 6, 8}

1.6 frozenset – Immutable Sets

A frozenset is an immutable version of a set. It is hashable, so it can be used as a dictionary key or as an element of another set.

fs = frozenset([1, 2, 3]) # fs.add(4) # AttributeError

2. Dictionaries – Powerful Key‑Value Mappings

2.1 Definition and Creation

A dictionary (dict) is an unordered, mutable collection of key‑value pairs. Each key must be hashable (immutable), and keys are unique within a dictionary.

person = {"name": "Alice", "age": 30, "city": "New York"}
empty_dict = {}
# From a list of tuples items = [("a", 1), ("b", 2)] d = dict(items) # {'a': 1, 'b': 2} # Using keyword arguments d = dict(name="Bob", age=25) # {'name': 'Bob', 'age': 25}
keys = ["x", "y", "z"] d = dict.fromkeys(keys, 0) # {'x': 0, 'y': 0, 'z': 0}

2.2 Accessing and Modifying Items

d = {"a": 1, "b": 2} print(d["a"]) # 1 print(d.get("c", 0)) # 0 (no KeyError) d["c"] = 3 # add d["a"] = 99 # update del d["b"] # remove 'b' value = d.pop("c") # returns 3, d is now {'a': 99}

2.3 Iteration and View Methods

Dictionaries are iterable; by default you iterate over keys.

Views are dynamic – they reflect changes to the dictionary.

for key in d: print(key, d[key]) for key, value in d.items(): print(key, value) # Convert to lists if needed list(d.keys()) # ['a', ...]

2.4 Other Useful Methods

d1 = {"a": 1, "b": 2} d2 = {"b": 3, "c": 4} d1.update(d2) # d1 becomes {'a': 1, 'b': 3, 'c': 4} d1.setdefault("d", 5) # adds key 'd' with value 5

2.5 Dictionary Comprehensions

Similar to list/set comprehensions:

squares = {x: x**2 for x in range(5)} # {0:0, 1:1, 2:4, 3:9, 4:16} even_squares = {x: x**2 for x in range(10) if x % 2 == 0}

2.6 Merging Dictionaries (Python 3.9+)

3. Comparing Sets and Dictionaries (and Other Collections)

Feature Set Dictionary List Tuple
Ordered? No (since Python 3.7, dicts preserve insertion order; sets are still unordered) Yes (insertion order preserved) Yes Yes
Mutable? Yes Yes Yes No
Indexable? No By key By integer By integer
Duplicate Elements? No (unique elements) No (unique keys; values can duplicate) Yes Yes
Hashable? No (set itself) No (dict itself) No Yes (if all elements hashable)
Use Cases Unique collection, membership, set ops Key‑value lookups, structured data Sequence of items Fixed sequence

📝 Quiz – Check Your Understanding

  1. How do you create an empty set in Python?

    Answer(B) `set()`
  2. What is the output of {1, 2, 3} & {2, 3, 4}?

    Answer(B) `{2, 3}`
  3. True or False: Dictionaries are unordered, so you cannot rely on the order of keys when iterating.

    AnswerFalse – since Python 3.7, dictionaries preserve insertion order.
  4. Which method returns the value for a key if it exists, otherwise returns a default without raising an error?

    Answer(B) `get()`
  5. What is the result of list({"a": 1, "b": 2}.keys())?

    Answer(B) `['a', 'b']`
  6. Which of the following can be a dictionary key?

    Answer(B) `(1, 2)` – tuples are hashable; lists and sets are not.
  7. What does s = {1, 2, 3}; s.discard(2) do?

    Answer(A) Removes `2` if present.
  8. What is the output of {x**2 for x in range(3)}?

    Answer(A) `{0, 1, 4}`
  9. How can you merge two dictionaries d1 and d2 (with d2 taking precedence) in Python 3.9+?

    Answer(D) All of the above.
  10. Which set operation returns elements that are in exactly one of the two sets?

    Answer(D) Symmetric difference

💻 Exercises – Practice Makes Perfect

Exercise 1: Set Operations
Given two sets:

A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8}

Write code to:

Sample Solution ```python print(A | B) # {1,2,3,4,5,6,7,8} print(A & B) # {4,5} print(A - B) # {1,2,3} print(B - A) # {6,7,8} print(A ^ B) # {1,2,3,6,7,8} print(A.issubset(B)) # False ```

Exercise 2: Remove Duplicates from a List
Write a function unique_elements(lst) that returns a new list with duplicates removed, preserving the order of first occurrence. Use a set to help, but note that sets are unordered; you need to preserve order. Hint: Use a loop and a set to track seen elements.

Sample Solution ```python def unique_elements(lst): seen = set() result = [] for item in lst: if item not in seen: seen.add(item) result.append(item) return result ```

Exercise 3: Word Frequency with Dictionary
Given the string text = "the quick brown fox jumps over the lazy dog the quick fox", write a program that:

Sample Solution ```python text = "the quick brown fox jumps over the lazy dog the quick fox" words = text.split() freq = {} for word in words: freq[word] = freq.get(word, 0) + 1 print(freq) max_count = max(freq.values()) most_frequent = [w for w, c in freq.items() if c == max_count] print("Most frequent:", most_frequent) ```

Exercise 4: Dictionary Manipulation
Create a dictionary inventory = {"apple": 10, "banana": 5, "orange": 8, "grape": 3}.

Sample Solution ```python inventory = {"apple": 10, "banana": 5, "orange": 8, "grape": 3} inventory["pear"] = 6 inventory["apple"] = 12 del inventory["grape"] print(inventory.keys()) print(inventory.values()) print(sum(inventory.values())) ```

Exercise 5: Set Comprehensions
Use a set comprehension to create:

Sample Solution ```python squares = {x**2 for x in range(10)} evens = {x for x in range(21) if x % 2 == 0} uppers = {ch for ch in "Hello World" if ch.isupper()} print(squares, evens, uppers) ```

🏠 Homework – Deeper Thinking

Short Answer Questions

1. Course Enrollment System
You are given two lists: students = ["Alice", "Bob", "Charlie", "Diana", "Eve"] and courses = ["Math", "Physics", "Chemistry"].
Create a dictionary where each student maps to a set of courses they are enrolled in (start empty). Write functions to:

Sample Answer ```python students = ["Alice", "Bob", "Charlie", "Diana", "Eve"] courses = ["Math", "Physics", "Chemistry"] enrollment = {s: set() for s in students}

def enroll(student, course): if student in enrollment: enrollment[student].add(course)

def drop(student, course): if student in enrollment: enrollment[student].discard(course)

def get_courses(student): return enrollment.get(student, set())

def get_students(course): return {s for s, cs in enrollment.items() if course in cs}

def common_courses(s1, s2): return get_courses(s1) & get_courses(s2)

def all_courses(): return set(courses)

</details> **2. Inverted Dictionary** Write a function `invert_dict(d)` that returns a new dictionary where the values become keys and the keys become values. If multiple keys have the same value, the inverted dictionary should map that value to a **set** of all original keys. <details><summary>Sample Answer</summary> ```python def invert_dict(d): inverted = {} for key, value in d.items(): inverted.setdefault(value, set()).add(key) return inverted

3. Anagram Finder
Write a function anagram_groups(words) that groups anagrams together using a dictionary.

Sample Answer ```python from collections import defaultdict def anagram_groups(words): groups = defaultdict(list) for word in words: key = ''.join(sorted(word)) groups[key].append(word) return list(groups.values()) ```

4. Set of Sets – Using Frozenset
Given a list of sets, write a function unique_sets(list_of_sets) that returns a list of unique sets (no duplicates). Use frozenset.

Sample Answer ```python def unique_sets(list_of_sets): seen = set() result = [] for s in list_of_sets: fs = frozenset(s) if fs not in seen: seen.add(fs) result.append(s) return result ```

Essay Questions

5. Character Frequency with Dictionary and Set
Write a program that reads a text file (or a multi‑line string) and computes:

Sample Answer ```python from collections import Counter def analyze_text(text): text = ''.join(text.split()) # remove whitespace total_chars = len(text) freq = Counter(text.lower()) unique_letters = set(freq.keys()) sorted_letters = sorted(freq.items(), key=lambda x: x[1], reverse=True) print("Total chars (excluding spaces):", total_chars) print("Unique letters:", unique_letters) print("Frequencies:", sorted_letters) ```

Homework Hints

Summary

In this tutorial, you have learned:

Sets and dictionaries are indispensable tools for writing efficient and clean Python code. With this knowledge, you can now handle unique collections and key‑value data with ease.

Next Steps: In Tutorial 6, we will cover File I/O and Exception Handling – reading and writing files, and managing errors gracefully.

Happy coding with sets and dictionaries!

Previous | Tutorial index | Next