Python,
Week 7
Sets and dictionaries: notation and properties, creating and modifying them, removing items, set operations, accessing dictionary values safely, and the dictionary methods.
Chapters
- 01Sets: Notation, Creating and AddingParts 1-2
- 02Removing Elements and Set OperationsParts 3-4
- 03Dictionaries: Notation, Creating and AccessingParts 5-6
- 04Changing, Adding and Removing ItemsPart 7
- 05Dictionary Methods and OperationsPart 8
- 06Try It YourselfPractice zone
- 07Week 7 Summary SheetAll parts
Sets: Notation, Creating and Adding
Curly braces without pairs, unique hashable items, set() for empty, add and update.
Lists and tuples (Week 6) keep items in order. A set throws the order away and keeps each value only once.
1.1Notation and properties
A set is an unordered collection of items. Every element is unique (no duplicates) and must itself be immutable (hashable), but the set object as a whole is mutable, so we can add or remove items from it.
| Property | Value |
|---|---|
| Notation | { } |
| Creation | set() |
| Mutability | Mutable |
| Types of elements stored | Hashable |
| Order of elements | Unordered |
| Duplicate elements | Not allowed |
| Operations | Add, delete |
| Sorting | Not in place (sorted() gives a list) |
Sets can also perform mathematical set operations like union, intersection and symmetric difference (Chapter 2).
1.2Creating sets
my_set = {1, 2, 3}
print(my_set)
my_set = {1.0, "Hello", (1, 2, 3)}
print(len(my_set))
my_set = {1, 2, 3, 4, 3, 2}
print(my_set)
my_set = set([1, 2, 3, 2])
print(my_set){1, 2, 3}
3
{1, 2, 3, 4}
{1, 2, 3}- A set can mix types: a float, a string and a tuple fit together (3 items).
- Duplicates are silently dropped.
- A set cannot hold a mutable item such as a list:
my_set = {1, 2, [3, 4]}TypeError: cannot use 'list' as a set element (unhashable type: 'list')unhashable type: 'list', the wording of older Python versions. Python 3.14 says it as above; the error type is the same.1.3The empty set
{} creates an empty dictionary, not a set. To make an empty set, use set() without any argument.
a = {}
print(type(a))
a = set()
print(type(a))<class 'dict'>
<class 'set'>1.4No indexing, but fast membership
Sets are mutable, but since they are unordered, indexing has no meaning: elements cannot be accessed or changed with [].
s = {10, 20, 30}
print(s[0])TypeError: 'set' object is not subscriptableWhat a set does very well is answer "is this value in it?" (extra):
s = {10, 20, 30}
print(20 in s, 25 in s)
print(len(s))True False
31.5Adding elements: add and update
We add a single element with add(), and multiple elements (from a tuple, list, string or another set) with update(). Duplicates are always avoided.
my_set = {1, 3}
my_set.add(2)
print(my_set)
my_set.update([2, 3, 4])
print(my_set)
my_set.update([4, 5], {1, 6, 8})
print(my_set){1, 2, 3}
{1, 2, 3, 4}
{1, 2, 3, 4, 5, 6, 8}The difference shows clearly with a tuple (extra): add puts the tuple in as one item, update adds each of its items.
s = {1}
s.add((2, 3))
print(s)
s.update((2, 3))
print(s){(2, 3), 1}
{(2, 3), 1, 2, 3}A string is a sequence of characters, so set("banana") keeps the three distinct letters:
letters = set("banana")
print(sorted(letters))
print(len(letters))['a', 'b', 'n']
3B.difference(A) prints {8, 6, 7}. Sets of strings can even print in a different order on every run, so these notes print them through sorted().1.6Exam tips and common mistakes
- Count distinct values to get the length of a set.
- Check the type of
{}: it is a dict.
- Writing
{}for an empty set. - Using
s[0]on a set. - Putting a list inside a set.
- Expecting a particular printed order.
Practice questions (graded-assignment style)
Numerical Answer Type (NAT).
What does the program print?
s = {3, 1, 3, 2, 1}
print(len(s))Duplicates are dropped.
s = {3, 1, 3, 2, 1}
print(len(s))3- The distinct values are 1, 2, 3.
- Answer: 3
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
a = {}
b = set()
print(type(a) == type(b)){} is a dict.
a = {}
b = set()
print(type(a) == type(b))Falseais a dict,ba set.- Answer: option 2.
Numerical Answer Type (NAT).
What does the program print?
s = {1, 2}
s.add(2)
s.update([3, 4], (4, 5))
print(len(s))update takes several iterables.
s = {1, 2}
s.add(2)
s.update([3, 4], (4, 5))
print(len(s))5- 2 is already there; update adds 3, 4 and 5 (4 only once).
- The set is {1, 2, 3, 4, 5}.
- Answer: 5
Numerical Answer Type (NAT).
What does the program print?
s = {1, 2}
s.add((3, 4))
print(len(s))add puts its argument in as one item.
s = {1, 2}
s.add((3, 4))
print(len(s))3- The tuple
(3, 4)is one element. - Answer: 3
Unordered, unique
Hashable items only
set() is a set
update(...): many
No duplicates
x in s: fast test
Removing Elements and Set Operations
discard against remove, pop and clear, and union, intersection, difference and their relatives.
2.1discard and remove
An item can be removed with discard() or remove(). The difference: discard() leaves the set unchanged if the element is not present, while remove() raises a KeyError.
my_set = {1, 3, 4, 5, 6}
my_set.discard(4)
print(my_set)
my_set.remove(6)
print(my_set)
my_set.discard(2)
print(my_set)
my_set.remove(2){1, 3, 5, 6}
{1, 3, 5}
{1, 3, 5}
KeyError: 22.2pop and clear
pop() removes and returns an item. Since a set is unordered, which item is popped is arbitrary. clear() removes all items at once.
s = {5, 3, 9}
x = s.pop()
print(x, s)
s.clear()
print(s)9 {3, 5}
set()Here Python happened to pop 9; do not write code that depends on which item comes out. Popping from an empty set is an error (extra):
s = set()
s.pop()KeyError: 'pop from an empty set'2.3Union, intersection, difference
Union (| or union()) collects all elements from both sets. Intersection (& or intersection()) returns the elements common to both. Difference (- or difference()) returns the elements only in the first set.
A = {1, 2, 3}
B = {1, 4, 6}
C = {8, 9}
print(A | B)
print(B.union(C))
print(A & B)
print(B.intersection(C))
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A - B)
print(B.difference(A)){1, 2, 3, 4, 6}
{1, 4, 6, 8, 9}
{1}
set()
{1, 2, 3}
{8, 6, 7}{6, 7, 8} for B.difference(A); Python 3.14 printed {8, 6, 7}. It is the same set: a set has no order.2.4Symmetric difference
The elements in either set but not in both: ^ or symmetric_difference(). It equals the union minus the intersection (extra check below).
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A ^ B)
print(A.symmetric_difference(B))
print((A | B) - (A & B)){1, 2, 3, 6, 7, 8}
{1, 2, 3, 6, 7, 8}
{1, 2, 3, 6, 7, 8}2.5Subset, superset, disjoint
| Method | Description | Operator |
|---|---|---|
isdisjoint() | True if two sets have a null intersection | — |
issubset() | True if the other set contains this set | <= |
issuperset() | True if this set contains the other set | >= |
symmetric_difference() | Elements in either set, but not both | ^ |
update() | Updates the set with the union of itself and others | |= |
A = {1, 2}
B = {1, 2, 3}
C = {7, 8}
print(A.issubset(B), A <= B)
print(B.issuperset(A), B >= A)
print(A.isdisjoint(C), A.isdisjoint(B))True True
True True
True FalseA = {1, 2}
A.update({2, 3}, [4])
print(A)
A |= {9}
print(A){1, 2, 3, 4}
{1, 2, 3, 4, 9}The operators |, &, -, ^ build a new set; update() and |= change the set in place.
2.6Sorting a set (extra)
s = {3, 1, 2}
print(sorted(s))
s.sort()[1, 2, 3]
AttributeError: 'set' object has no attribute 'sort'A set has no sort(); sorted(s) returns a sorted list.
n × m comparisons). In Python, set(l1) & set(l2) gives the overlap directly (without repeats and without order).2.7Exam tips and common mistakes
- Draw a quick Venn diagram for every set expression.
- A - B and B - A are different.
- Using
removewhen the element may be missing. - Thinking
popremoves the first or last item. - Confusing
issubsetandissuperset.
Practice questions (graded-assignment style)
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
A = {1, 2, 3, 4}
B = {3, 4, 5}
print(len(A | B), len(A & B), len(A - B))Work out each set.
A = {1, 2, 3, 4}
B = {3, 4, 5}
print(len(A | B), len(A & B), len(A - B))5 2 2- Union {1..5}: 5; intersection {3, 4}: 2; A - B {1, 2}: 2.
- Answer: option 1.
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
A = {1, 2, 3}
B = {2, 3, 4}
print(sorted(A ^ B))[2, 3][1, 2, 3, 4][1, 4][]In one set but not both.
A = {1, 2, 3}
B = {2, 3, 4}
print(sorted(A ^ B))[1, 4]- 2 and 3 are in both; 1 and 4 in one only.
- Answer: option 3.
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
s = {1, 2, 3}
s.discard(5)
s.remove(1)
print(s){1, 2, 3}{2, 3}{1, 2}discard(5) is harmless.
s = {1, 2, 3}
s.discard(5)
s.remove(1)
print(s){2, 3}- 5 is missing, so nothing happens; then 1 is removed.
- Answer: option 2.
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
A = {1, 2}
B = {1, 2, 3}
print(B.issubset(A), A <= B, A.isdisjoint({3}))B is bigger than A.
A = {1, 2}
B = {1, 2, 3}
print(B.issubset(A), A <= B, A.isdisjoint({3}))False True True- B is not a subset of A; A is a subset of B; A and {3} share nothing.
- Answer: option 4.
remove: KeyError
pop: arbitrary item
- difference
^ symmetric difference
issuperset (>=)
isdisjoint
sorted(s) gives a list
Dictionaries: Notation, Creating and Accessing
Key: value pairs, creating them, [] against get(), and the rules for keys.
3.1Notation and properties
A Python dictionary is a collection of items, where each item is a key: value pair. Dictionaries are optimised to retrieve a value when the key is known.
| Property | Value |
|---|---|
| Notation | {'key': 'value'} |
| Creation | d = {} or dict() |
| Mutability | Mutable |
| Types stored | Keys: hashable · Values: any |
| Order of elements | Insertion order (Python 3.7+) |
| Duplicate elements | Keys: not allowed · Values: allowed |
| Operations | Keys: add, delete · Values: add, update, delete |
| Sorting | Not in place; sorted(d) gives the sorted keys |
3.2Creating a dictionary
An item has a key and a corresponding value, expressed as key: value. Values can repeat, but keys must be of an immutable type (string, number, or a tuple of immutables) and must be unique.
d = {}
d = {1: 'apple', 2: 'ball'}
print(d)
d = {'name': 'John', 1: [2, 3]}
print(d)
d = dict({1: 'A', 2: 'B'})
print(d)
d = dict([(1, 'A'), (2, 'B')])
print(d){1: 'apple', 2: 'ball'}
{'name': 'John', 1: [2, 3]}
{1: 'A', 2: 'B'}
{1: 'A', 2: 'B'}dict() also accepts keyword arguments when the keys are simple names (extra):
d = dict(name='Asha', age=19)
print(d){'name': 'Asha', 'age': 19}3.3Accessing values: [] and get()
A dictionary uses keys to access values, either with square brackets [] or with get(). If a key is not found, [] raises a KeyError, while get() quietly returns None.
d = {'name': 'Jack', 'age': 26}
print(d['name'])
print(d.get('age'))
print(d.get('address'))
print(d['address'])Jack
26
None
KeyError: 'address'get() also takes a default to return instead of None (extra):
d = {'name': 'Jack', 'age': 26}
print(d.get('address', 'not given'))
print(d.get('age', 0))not given
263.4Rules for keys
d = {}
d[[1, 2]] = 'x' TypeError: cannot use 'list' as a dict key (unhashable type: 'list')d = {}
d[(1, 2)] = 'x'
print(d){(1, 2): 'x'}A key must be hashable: a list cannot be a key, a tuple of immutables can. Two traps about uniqueness (extra):
d = {'a': 1, 'b': 2, 'a': 3}
print(d){'a': 3, 'b': 2}A repeated key keeps the last value (and the position of the first). And keys that are equal count as the same key, even with different types:
d = {1: 'a', True: 'b', 1.0: 'c'}
print(d){1: 'c'}1 == True == 1.0 in Python, so all three are one key: the first spelling of the key stays and the last value wins.
isKey(d, k) is k in d, keys(d) is d.keys(), and reading a missing key is the KeyError above.3.5Exam tips and common mistakes
- For a missing key,
[]means an error andgetmeans None. - When keys repeat, the last value wins.
- Using a list as a key.
- Expecting
d.get(k)to raise an error. - Forgetting that 1 and True are the same key.
Practice questions (graded-assignment style)
Numerical Answer Type (NAT).
What does the program print?
d = {'a': 1, 'b': 2}
print(d.get('c', 0) + d['b'])get returns the default for a missing key.
d = {'a': 1, 'b': 2}
print(d.get('c', 0) + d['b'])2d.get('c', 0)is 0 andd['b']is 2.- Answer: 2
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
d = {1: 'x', 1.0: 'y', 2: 'z'}
print(len(d), d[1])1 and 1.0 are the same key.
d = {1: 'x', 1.0: 'y', 2: 'z'}
print(len(d), d[1])2 y- Two keys remain; key 1 now holds 'y'.
- Answer: option 2.
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
d = dict([('p', 1), ('q', 2)])
print(d.get('r'))get never raises for a missing key.
d = dict([('p', 1), ('q', 2)])
print(d.get('r'))None- 'r' is not a key, so
None. - Answer: option 1.
Keys unique, hashable
Insertion order (3.7+)
dict of pairs
dict(name=...)
d.get(k): None
d.get(k, default)
Last value wins
1 == True == 1.0
Changing, Adding and Removing Items
Assignment to a key, pop, popitem (last in, first out), clear and del.
4.1Changing and adding
Dictionaries are mutable: we add or change values with the assignment operator. If the key already exists, its value is updated; otherwise a new pair is added.
d = {'name': 'John', 'age': 26}
d['age'] = 27
d['address'] = 'Downtown'
print(d){'name': 'John', 'age': 27, 'address': 'Downtown'}4.2Removing items
pop(key) removes an item and returns its value; popitem() removes and returns a (key, value) pair; clear() empties the dictionary; del removes an individual item or the whole dictionary.
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
print(squares.pop(4))
print(squares.popitem())
print(squares)
squares.clear()
print(squares)
del squares
print(squares)16
(5, 25)
{1: 1, 2: 4, 3: 9}
{}
NameError: name 'squares' is not definedAfter del squares the name no longer exists, so printing it is a NameError, not an empty dictionary.
4.3popitem removes the last pair added
popitem() removes an arbitrary pair. That was true before Python 3.7. Now it always removes the most recently inserted pair (last in, first out), as the run shows: (5, 25) was the last pair.d = {'a': 1, 'b': 2}
d['c'] = 3
print(d.popitem())
print(d.popitem())
print(d)('c', 3)
('b', 2)
{'a': 1}4.4pop with a default, and del for one key (extra)
d = {'a': 1}
print(d.pop('z', 'missing'))
print(d.pop('z'))missing
KeyError: 'z'Like get, pop takes a default for a missing key; without one it raises KeyError. del d[k] removes one key without returning anything:
d = {'a': 1, 'b': 2}
del d['a']
print(d){'b': 2}4.5Exam tips and common mistakes
- Assignment to a key: update if present, add if not.
- Follow insertion order to predict
popitem().
- Expecting
popitem()to pick a random pair. - Printing a dictionary after
delof its name. - Calling
pop()with no key on a dictionary.
Practice questions (graded-assignment style)
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
d = {'a': 1, 'b': 2, 'c': 3}
x = d.pop('b')
y = d.popitem()
print(x, y, d)popitem takes the last pair still there.
d = {'a': 1, 'b': 2, 'c': 3}
x = d.pop('b')
y = d.popitem()
print(x, y, d)2 ('c', 3) {'a': 1}pop('b')gives 2; then the last pair is ('c', 3).- Answer: option 3.
Numerical Answer Type (NAT).
What does the program print?
d = {'a': 1}
d['a'] = d['a'] + 5
d['b'] = d['a'] * 2
print(sum(d.values()))Trace the values.
d = {'a': 1}
d['a'] = d['a'] + 5
d['b'] = d['a'] * 2
print(sum(d.values()))18d['a']becomes 6,d['b']12.- 6 + 12.
- Answer: 18
Update or add
popitem(): last pair
clear(), del
del name: NameError later
Dictionary Methods and Operations
fromkeys, items, keys, values, setdefault, update, copy, in, iteration and sorting.
Beyond get(), pop() and popitem(): fromkeys(), items(), keys(), values(), setdefault(), update(), copy(), clear().
5.1fromkeys, items and sorted keys
marks = {}.fromkeys(['Math', 'English', 'Science'], 0)
print(marks)
for item in marks.items():
print(item)
print(list(sorted(marks.keys()))){'Math': 0, 'English': 0, 'Science': 0}
('Math', 0)
('English', 0)
('Science', 0)
['English', 'Math', 'Science']sorted() already returns a list, so the list(...) around it in the source is not needed (extra). One trap with fromkeys: every key gets the same value object, which matters when that value is a list:
d = dict.fromkeys(['a', 'b'], [])
d['a'].append(1)
print(d){'a': [1], 'b': [1]}5.2keys, values, setdefault, update, copy
d = {'x': 10, 'y': 20, 'z': 30}
print(d.keys())
print(d.values())
print(list(d.keys()), sum(d.values()))dict_keys(['x', 'y', 'z'])
dict_values([10, 20, 30])
['x', 'y', 'z'] 60keys() and values() give views; wrap them in list() to get a list, or use them directly in loops and with sum, len, in.
d = {'a': 1}
print(d.setdefault('a', 100))
print(d.setdefault('b', 100))
print(d)1
100
{'a': 1, 'b': 100}setdefault(k, v) returns the value of k if it exists; otherwise it adds k: v and returns v.
d = {'a': 1, 'b': 2}
d.update({'b': 20, 'c': 3})
print(d){'a': 1, 'b': 20, 'c': 3}update() overwrites existing keys and adds new ones. copy() makes a new dictionary, unlike plain assignment:
d = {'a': 1}
alias = d
c = d.copy()
d['b'] = 2
print(alias)
print(c){'a': 1, 'b': 2}
{'a': 1}5.3Membership and iteration
Membership testing with in checks only the keys, never the values. We can also iterate through the keys of a dictionary directly with a for loop.
squares = {1: 1, 2: 4, 4: 16}
print(1 in squares)
print(16 in squares)
print(16 in squares.values())True
False
Truesquares = {1: 1, 3: 9, 5: 25, 7: 49}
for i in squares:
print(squares[i])1
9
25
49To get each key with its value, loop over items() and unpack the pairs (extra):
squares = {1: 1, 3: 9, 5: 25}
for k, v in squares.items():
print(k, "->", v)1 -> 1
3 -> 9
5 -> 25Adding or removing keys while looping over the same dictionary is not allowed (extra):
d = {1: 1, 2: 4}
for k in d:
d[k + 10] = 0RuntimeError: dictionary changed size during iterationLoop over list(d) instead if keys must be added or removed inside the loop.
5.4Sorting by key or by value (extra)
d = {'b': 2, 'c': 1, 'a': 3}
print(sorted(d))
print(sorted(d.items()))
print(sorted(d, key=d.get))['a', 'b', 'c']
[('a', 3), ('b', 2), ('c', 1)]
['c', 'b', 'a']sorted(d) sorts the keys; sorted(d.items()) sorts the pairs by key; sorted(d, key=d.get) orders the keys by their values.
5.5Exam tips and common mistakes
inon a dictionary: keys only.- Counting words:
d[w] = d.get(w, 0) + 1.
- Expecting
16 in squaresto find a value. - Sharing one list through
fromkeys. - Changing the size of a dictionary inside a loop over it.
Practice questions (graded-assignment style)
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
d = {1: 10, 2: 20}
print(10 in d, 2 in d)Keys only.
d = {1: 10, 2: 20}
print(10 in d, 2 in d)False True- 10 is a value, 2 is a key.
- Answer: option 2.
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
d = {}.fromkeys('ab', 0)
d.update({'b': 5, 'c': 7})
print(d){'ab': 0, 'b': 5, 'c': 7}{'a': 0, 'b': 0, 'c': 7}{'b': 5, 'c': 7}{'a': 0, 'b': 5, 'c': 7}fromkeys of a string uses its characters.
d = {}.fromkeys('ab', 0)
d.update({'b': 5, 'c': 7})
print(d){'a': 0, 'b': 5, 'c': 7}- Start {'a': 0, 'b': 0}; update changes b and adds c.
- Answer: option 4.
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
d = {'a': 1}
d.setdefault('a', 9)
d.setdefault('b', 9)
print(d){'a': 1, 'b': 9}{'a': 9, 'b': 9}{'a': 1}{'b': 9}setdefault never overwrites.
d = {'a': 1}
d.setdefault('a', 9)
d.setdefault('b', 9)
print(d){'a': 1, 'b': 9}- 'a' exists and stays 1; 'b' is added with 9.
- Answer: option 1.
Numerical Answer Type (NAT).
What does the program print?
words = ['x', 'y', 'x', 'x']
c = {}
for w in words:
c[w] = c.get(w, 0) + 1
print(c['x'] - c['y'])Count each word.
words = ['x', 'y', 'x', 'x']
c = {}
for w in words:
c[w] = c.get(w, 0) + 1
print(c['x'] - c['y'])2- x appears 3 times, y once.
- Answer: 2
setdefault(k, v)
update(other)
in: keys only
for k, v in d.items()
No size change inside
sorted(d, key=d.get)
Try It Yourself
The seven tasks of the source, each with an executed solution.
Seven tasks from the source, to be done without looking back at the examples. Each has a really executed solution.
Create two sets of numbers and print their union, intersection and difference.
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print(A | B)
print(A & B)
print(A - B){1, 2, 3, 4, 5, 6}
{3, 4}
{1, 2}Show what happens when discard() and remove() are both called on an element that is not in the set.
s = {1, 2, 3}
s.discard(10)
print(s){1, 2, 3}s = {1, 2, 3}
s.remove(10)KeyError: 10discard quietly does nothing; remove raises KeyError.
Convert a list with duplicate values into a set, and explain what happens to the duplicates.
nums = [1, 2, 2, 3, 3, 3]
unique = set(nums)
print(unique){1, 2, 3}Each value is kept once; the order of the list is not kept.
Build a dictionary of 3 students and their marks, then update one mark and add a new student.
marks = {'Asha': 88, 'Rahul': 76, 'Mei': 91}
marks['Rahul'] = 80
marks['Zara'] = 85
print(marks){'Asha': 88, 'Rahul': 80, 'Mei': 91, 'Zara': 85}Rahul is updated in place; Zara is added at the end (insertion order).
Look up a missing key with both get() and [], and explain the difference in behaviour.
d = {'a': 1}
print(d.get('b'))Noned = {'a': 1}
print(d['b'])KeyError: 'b'get returns None; [] raises KeyError.
Iterate over a dictionary's items() and print each key alongside its value doubled.
scores = {'x': 10, 'y': 20}
for k, v in scores.items():
print(k, v * 2)x 20
y 40Given a list of words, build a dictionary counting how many times each word appears.
words = ['cat', 'dog', 'cat', 'bird', 'dog', 'cat']
counts = {}
for w in words:
counts[w] = counts.get(w, 0) + 1
print(counts){'cat': 3, 'dog': 2, 'bird': 1}counts.get(w, 0) starts a new word at 0. This is CT Week 7's accumulator pattern in one line.
Week 7 Summary Sheet
One page to revise all of Week 7: dictionary vs set, the methods, the patterns and the errors.
7.1Dictionary vs set
| Property | Dictionary | Set |
|---|---|---|
| Notation | {'K': 'V'} | {1, 2} |
| Creation | dict() | set() |
| Mutability | Mutable | Mutable |
| Elements stored | Keys: hashable · Values: any | Hashable |
| Order | Insertion order (3.7+) | Unordered |
| Duplicates | Keys: no · Values: yes | Not allowed |
| Operations | Keys: add/delete · Values: add/update/delete | Add, delete |
| Indexing / slicing | No positions; access by key | No; iteration only |
| Sorting | sorted(d) gives sorted keys | sorted(s) gives a list |
| Empty | {} | set() |
7.2Methods side by side
| Dictionary methods | Set methods |
|---|---|
clear(), copy() | add(), update() |
fromkeys(), get() | discard(), remove(), pop() |
items(), keys(), values() | union(), intersection(), difference() |
pop(), popitem() | issubset(), issuperset(), isdisjoint() |
setdefault(), update() | symmetric_difference(), clear(), copy() |
Patterns and how to use them
unique = set(items)Use whenYou only care which values occur, not how often or in what order.
set(items)keeps each value once.- Use
sorted(...)for a stable order. - Use
len(...)to count distinct values.
marks = [70, 85, 70, 92, 85]
print(sorted(set(marks)), len(set(marks)))[70, 85, 92] 3both = A & B
only_A = A - B
either = A | BUse whenComparing two groups.
- Turn the lists into sets.
- & for common, - for only in the first, | for all.
- ^ for in exactly one.
a = {"CT", "Maths", "Stats"}
b = {"CT", "Python"}
print(a & b, len(a | b)){'CT'} 4value = d.get(key, default)Use whenThe key might be missing and an error would be wrong.
d[k]when the key must exist.d.get(k)for None if missing.d.get(k, v)for your own default.
marks = {"Asha": 88}
print(marks.get("Ravi", "absent"))absentcounts[w] = counts.get(w, 0) + 1Use whenCounting how often each value appears.
- Start with
counts = {}. - For each item add 1 to
counts.get(item, 0). - Read the counts with
items().
counts = {}
for ch in "banana":
counts[ch] = counts.get(ch, 0) + 1
print(counts){'b': 1, 'a': 3, 'n': 2}for k, v in d.items():
...Use whenYou need both the key and the value.
items()gives (key, value) pairs.- Unpack them in the for line.
- Do not add or remove keys inside the loop.
d = {"a": 10, "b": 20}
for k, v in d.items():
print(k, v + 5)a 15
b 25v = d.pop(k)
k, v = d.popitem()Use whenYou need the removed value, or to undo the last addition.
pop(k)returns the value.popitem()takes the last pair added.del d[k]just deletes.
d = {"x": 1}
d["y"] = 2
print(d.popitem(), d)('y', 2) {'x': 1}7.3Common errors to avoid
| Mistake | What Python says |
|---|---|
{1, 2, [3, 4]} | TypeError: cannot use 'list' as a set element (unhashable type: 'list') |
s[0] on a set | TypeError: 'set' object is not subscriptable |
s.remove(2), 2 not in s | KeyError: 2 |
set().pop() | KeyError: 'pop from an empty set' |
d['address'], missing key | KeyError: 'address' |
| a list as a key | TypeError: cannot use 'list' as a dict key (unhashable type: 'list') |
printing after del squares | NameError: name 'squares' is not defined |
| adding keys while looping | RuntimeError: dictionary changed size during iteration |
| Mistake | Correct idea |
|---|---|
{} for an empty set | {} is a dict; use set(). |
popitem() is random | It removes the last pair added (Python 3.7+). |
16 in squares to find a value | in checks keys; use 16 in squares.values(). |
dict.fromkeys(keys, []) | All keys share one list. |
| Expecting a fixed set order | Sets have none; print through sorted(). |
7.4Last-minute checklist
- Set notation, uniqueness, and why
{}makes a dict, not a set add()vsupdate(), anddiscard()vsremove()- Set operations: union, intersection, difference and their operators
- Dictionary key: value pairs, and the key immutability and uniqueness rules
get()vs[]for missing keyspop(),popitem(),clear()anddelon dictionaries- Membership test (
in) checks keys only, never values - Dictionary methods:
fromkeys(),items(),keys(),sorted() - The full property comparison: dictionary vs set
Unique, unordered
add, update
| & - ^
subset, superset
[] vs get()
Insertion order
pop, popitem (last)
clear, del
in: keys only
get(w, 0) + 1