Weeks
Intro to PythonWeek 7 · Sets and Dictionaries
Week 7 Notes

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.

7 chapters24 worked examples~23 min read
SetsSet operationsDictionariesget()Dictionary methods

Chapters

  1. 01Sets: Notation, Creating and AddingParts 1-2
  2. 02Removing Elements and Set OperationsParts 3-4
  3. 03Dictionaries: Notation, Creating and AccessingParts 5-6
  4. 04Changing, Adding and Removing ItemsPart 7
  5. 05Dictionary Methods and OperationsPart 8
  6. 06Try It YourselfPractice zone
  7. 07Week 7 Summary SheetAll parts
01
Sets

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

Set

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.

PropertyValue
Notation{ }
Creationset()
MutabilityMutable
Types of elements storedHashable
Order of elementsUnordered
Duplicate elementsNot allowed
OperationsAdd, delete
SortingNot in place (sorted() gives a list)

Sets can also perform mathematical set operations like union, intersection and symmetric difference (Chapter 2).

1.2Creating sets

Python
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)
Output
{1, 2, 3}
3
{1, 2, 3, 4}
{1, 2, 3}
list with repeats[1232]set(...)each value once{123}
Figure 1. set([1, 2, 3, 2]) keeps each value once
  • 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:
Python
my_set = {1, 2, [3, 4]}
Error
TypeError: cannot use 'list' as a set element (unhashable type: 'list')
Error wording. The source shows a TypeError with the message 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.

Python
a = {}
print(type(a))
a = set()
print(type(a))
Output
<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 [].

Python
s = {10, 20, 30}
print(s[0])
Error
TypeError: 'set' object is not subscriptable

What a set does very well is answer "is this value in it?" (extra):

Python
s = {10, 20, 30}
print(20 in s, 25 in s)
print(len(s))
Output
True False
3

1.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.

Python
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)
Output
{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.

Python
s = {1}
s.add((2, 3))
print(s)
s.update((2, 3))
print(s)
Output
{(2, 3), 1}
{(2, 3), 1, 2, 3}

A string is a sequence of characters, so set("banana") keeps the three distinct letters:

Python
letters = set("banana")
print(sorted(letters))
print(len(letters))
Output
['a', 'b', 'n']
3
Printed order. A set has no order. Python prints sets of small integers in a tidy-looking order, but that is not guaranteed: in Chapter 2, B.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

Exam tips
  • Count distinct values to get the length of a set.
  • Check the type of {}: it is a dict.
Common mistakes
  • 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)

Q1Distinct values

Numerical Answer Type (NAT).

What does the program print?

Python
s = {3, 1, 3, 2, 1}
print(len(s))
Solution
Idea

Duplicates are dropped.

Python
s = {3, 1, 3, 2, 1}
print(len(s))
Output
3
  • The distinct values are 1, 2, 3.
  • Answer: 3
Q2Empty braces

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
a = {}
b = set()
print(type(a) == type(b))
1
True
2
False
3
An error
4
None
Solution
Idea

{} is a dict.

Python
a = {}
b = set()
print(type(a) == type(b))
Output
False
  • a is a dict, b a set.
  • Answer: option 2.
Q3add and update

Numerical Answer Type (NAT).

What does the program print?

Python
s = {1, 2}
s.add(2)
s.update([3, 4], (4, 5))
print(len(s))
Solution
Idea

update takes several iterables.

Python
s = {1, 2}
s.add(2)
s.update([3, 4], (4, 5))
print(len(s))
Output
5
  • 2 is already there; update adds 3, 4 and 5 (4 only once).
  • The set is {1, 2, 3, 4, 5}.
  • Answer: 5
Q4add a tuple

Numerical Answer Type (NAT).

What does the program print?

Python
s = {1, 2}
s.add((3, 4))
print(len(s))
Solution
Idea

add puts its argument in as one item.

Python
s = {1, 2}
s.add((3, 4))
print(len(s))
Output
3
  • The tuple (3, 4) is one element.
  • Answer: 3
Revision overview
Set{ } or set()
Unordered, unique
Hashable items only
Empty{} is a dict
set() is a set
SetsParts 1-2
Addingadd(x): one item
update(...): many
No duplicates
AccessNo indexing
x in s: fast test
Revision: what a set is and how to fill it
Next · SetsRemoving Elements and Set Operations
02
Sets

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.

Python
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)
Error
{1, 3, 5, 6}
{1, 3, 5}
{1, 3, 5}
KeyError: 2
s = {1, 3, 5}, element 2 is missings.discard(2)nothing happenss.remove(2)KeyError: 2
Figure 2. For a missing element, discard does nothing and remove raises KeyError

2.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.

Python
s = {5, 3, 9}
x = s.pop()
print(x, s)
s.clear()
print(s)
Output
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):

Python
s = set()
s.pop()
Error
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.

Python
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))
Output
{1, 2, 3, 4, 6}
{1, 4, 6, 8, 9}
{1}
set()
{1, 2, 3}
{8, 6, 7}
Printed order again. The source shows {6, 7, 8} for B.difference(A); Python 3.14 printed {8, 6, 7}. It is the same set: a set has no order.
1 2 34 56 7 8ABA | Bunion{1, ..., 8}1 2 34 56 7 8ABA & Bintersection{4, 5}1 2 34 56 7 8ABA - Bdifference{1, 2, 3}1 2 34 56 7 8ABA ^ Bsymmetric difference{1, 2, 3, 6, 7, 8}
Figure 3. The four operations on A = {1, 2, 3, 4, 5} and B = {4, 5, 6, 7, 8}

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).

Python
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))
Output
{1, 2, 3, 6, 7, 8}
{1, 2, 3, 6, 7, 8}
{1, 2, 3, 6, 7, 8}

2.5Subset, superset, disjoint

MethodDescriptionOperator
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|=
Python
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))
Output
True True
True True
True False
1 23B = {1, 2, 3}A7 8C = {7, 8}A <= B: A.issubset(B)B >= A: B.issuperset(A)A, C share nothing: isdisjoint
Figure 4. A inside B: subset and superset; A and C share nothing: disjoint
Python
A = {1, 2}
A.update({2, 3}, [4])
print(A)
A |= {9}
print(A)
Output
{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)

Python
s = {3, 1, 2}
print(sorted(s))
s.sort()
Error
[1, 2, 3]
AttributeError: 'set' object has no attribute 'sort'

A set has no sort(); sorted(s) returns a sorted list.

Link to Computational Thinking (extra). CT Week 8 found the overlap of two lists with nested loops (n × m comparisons). In Python, set(l1) & set(l2) gives the overlap directly (without repeats and without order).

2.7Exam tips and common mistakes

Exam tips
  • Draw a quick Venn diagram for every set expression.
  • A - B and B - A are different.
Common mistakes
  • Using remove when the element may be missing.
  • Thinking pop removes the first or last item.
  • Confusing issubset and issuperset.

Practice questions (graded-assignment style)

Q1Three sizes

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
A = {1, 2, 3, 4}
B = {3, 4, 5}
print(len(A | B), len(A & B), len(A - B))
1
5 2 2
2
7 2 2
3
5 2 1
4
5 3 2
Solution
Idea

Work out each set.

Python
A = {1, 2, 3, 4}
B = {3, 4, 5}
print(len(A | B), len(A & B), len(A - B))
Output
5 2 2
  • Union {1..5}: 5; intersection {3, 4}: 2; A - B {1, 2}: 2.
  • Answer: option 1.
Q2Symmetric difference

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
A = {1, 2, 3}
B = {2, 3, 4}
print(sorted(A ^ B))
1
[2, 3]
2
[1, 2, 3, 4]
3
[1, 4]
4
[]
Solution
Idea

In one set but not both.

Python
A = {1, 2, 3}
B = {2, 3, 4}
print(sorted(A ^ B))
Output
[1, 4]
  • 2 and 3 are in both; 1 and 4 in one only.
  • Answer: option 3.
Q3discard then remove

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
s = {1, 2, 3}
s.discard(5)
s.remove(1)
print(s)
1
{1, 2, 3}
2
{2, 3}
3
KeyError: 5
4
{1, 2}
Solution
Idea

discard(5) is harmless.

Python
s = {1, 2, 3}
s.discard(5)
s.remove(1)
print(s)
Output
{2, 3}
  • 5 is missing, so nothing happens; then 1 is removed.
  • Answer: option 2.
Q4Subset tests

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
A = {1, 2}
B = {1, 2, 3}
print(B.issubset(A), A <= B, A.isdisjoint({3}))
1
True True True
2
False True False
3
True False True
4
False True True
Solution
Idea

B is bigger than A.

Python
A = {1, 2}
B = {1, 2, 3}
print(B.issubset(A), A <= B, A.isdisjoint({3}))
Output
False True True
  • B is not a subset of A; A is a subset of B; A and {3} share nothing.
  • Answer: option 4.
Revision overview
Removingdiscard: no error
remove: KeyError
pop: arbitrary item
Operations| union, & intersection
- difference
^ symmetric difference
Set operationsParts 3-4
Relationsissubset (<=)
issuperset (>=)
isdisjoint
In placeupdate(), |=
sorted(s) gives a list
Revision: removing from sets and combining them
Next · DictionariesDictionaries: Notation, Creating and Accessing
03
Dictionaries

Dictionaries: Notation, Creating and Accessing

Key: value pairs, creating them, [] against get(), and the rules for keys.

3.1Notation and properties

Dictionary

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.

PropertyValue
Notation{'key': 'value'}
Creationd = {} or dict()
MutabilityMutable
Types storedKeys: hashable · Values: any
Order of elementsInsertion order (Python 3.7+)
Duplicate elementsKeys: not allowed · Values: allowed
OperationsKeys: add, delete · Values: add, update, delete
SortingNot in place; sorted(d) gives the sorted keys
Order. The source lists dictionaries as unordered, adding that this was true up to Python 3.6. From Python 3.7 on, a dictionary keeps its items in the order they were inserted, and every example here relies on that.

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.

Python
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)
Output
{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):

Python
d = dict(name='Asha', age=19)
print(d)
Output
{'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.

Python
d = {'name': 'Jack', 'age': 26}
print(d['name'])
print(d.get('age'))
print(d.get('address'))
print(d['address'])
Error
Jack
26
None
KeyError: 'address'
d = {'name': 'Jack', 'age': 26}'name''Jack''age'26d['age'] → 26d.get('age') → 26d['address'] → KeyErrord.get('address') → None (or a default)
Figure 5. A missing key: [] raises KeyError, get() returns None

get() also takes a default to return instead of None (extra):

Python
d = {'name': 'Jack', 'age': 26}
print(d.get('address', 'not given'))
print(d.get('age', 0))
Output
not given
26

3.4Rules for keys

Python
d = {}
d[[1, 2]] = 'x' 
Error
TypeError: cannot use 'list' as a dict key (unhashable type: 'list')
Python
d = {}
d[(1, 2)] = 'x'
print(d)
Output
{(1, 2): 'x'}

A key must be hashable: a list cannot be a key, a tuple of immutables can. Two traps about uniqueness (extra):

Python
d = {'a': 1, 'b': 2, 'a': 3}
print(d)
Output
{'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:

Python
d = {1: 'a', True: 'b', 1.0: 'c'}
print(d)
Output
{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.

Link to Computational Thinking Week 7 (extra). The CT dictionaries are these Python dictionaries: 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

Exam tips
  • For a missing key, [] means an error and get means None.
  • When keys repeat, the last value wins.
Common mistakes
  • 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)

Q1get with a default

Numerical Answer Type (NAT).

What does the program print?

Python
d = {'a': 1, 'b': 2}
print(d.get('c', 0) + d['b'])
Solution
Idea

get returns the default for a missing key.

Python
d = {'a': 1, 'b': 2}
print(d.get('c', 0) + d['b'])
Output
2
  • d.get('c', 0) is 0 and d['b'] is 2.
  • Answer: 2
Q2Equal keys

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
d = {1: 'x', 1.0: 'y', 2: 'z'}
print(len(d), d[1])
1
3 x
2
2 y
3
2 x
4
3 y
Solution
Idea

1 and 1.0 are the same key.

Python
d = {1: 'x', 1.0: 'y', 2: 'z'}
print(len(d), d[1])
Output
2 y
  • Two keys remain; key 1 now holds 'y'.
  • Answer: option 2.
Q3Missing key with get

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
d = dict([('p', 1), ('q', 2)])
print(d.get('r'))
1
None
2
KeyError: 'r'
3
0
4
''
Solution
Idea

get never raises for a missing key.

Python
d = dict([('p', 1), ('q', 2)])
print(d.get('r'))
Output
None
  • 'r' is not a key, so None.
  • Answer: option 1.
Revision overview
Dictionarykey: value pairs
Keys unique, hashable
Insertion order (3.7+)
Creating{} or dict()
dict of pairs
dict(name=...)
DictionariesParts 5-6
Accessd[k]: KeyError if missing
d.get(k): None
d.get(k, default)
KeysNo lists
Last value wins
1 == True == 1.0
Revision: building a dictionary and reading it safely
Next · DictionariesChanging, Adding and Removing Items
04
Dictionaries

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.

Python
d = {'name': 'John', 'age': 26}
d['age'] = 27
d['address'] = 'Downtown'
print(d)
Output
{'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.

Python
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)
Error
16
(5, 25)
{1: 1, 2: 4, 3: 9}
{}
NameError: name 'squares' is not defined

After del squares the name no longer exists, so printing it is a NameError, not an empty dictionary.

4.3popitem removes the last pair added

Correction. The source says 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.
Python
d = {'a': 1, 'b': 2}
d['c'] = 3
print(d.popitem())
print(d.popitem())
print(d)
Output
('c', 3)
('b', 2)
{'a': 1}
insertion order'a'1'b'2'c'3('c', 3)popitem() takes the last pair addedd['c'] = 3 was added last
Figure 6. popitem() returns and removes the pair added last

4.4pop with a default, and del for one key (extra)

Python
d = {'a': 1}
print(d.pop('z', 'missing'))
print(d.pop('z'))
Error
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:

Python
d = {'a': 1, 'b': 2}
del d['a']
print(d)
Output
{'b': 2}

4.5Exam tips and common mistakes

Exam tips
  • Assignment to a key: update if present, add if not.
  • Follow insertion order to predict popitem().
Common mistakes
  • Expecting popitem() to pick a random pair.
  • Printing a dictionary after del of its name.
  • Calling pop() with no key on a dictionary.

Practice questions (graded-assignment style)

Q1pop and popitem

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
d = {'a': 1, 'b': 2, 'c': 3}
x = d.pop('b')
y = d.popitem()
print(x, y, d)
1
2 ('a', 1) {'c': 3}
2
2 ('b', 2) {'a': 1}
3
2 ('c', 3) {'a': 1}
4
An error
Solution
Idea

popitem takes the last pair still there.

Python
d = {'a': 1, 'b': 2, 'c': 3}
x = d.pop('b')
y = d.popitem()
print(x, y, d)
Output
2 ('c', 3) {'a': 1}
  • pop('b') gives 2; then the last pair is ('c', 3).
  • Answer: option 3.
Q2Update and add

Numerical Answer Type (NAT).

What does the program print?

Python
d = {'a': 1}
d['a'] = d['a'] + 5
d['b'] = d['a'] * 2
print(sum(d.values()))
Solution
Idea

Trace the values.

Python
d = {'a': 1}
d['a'] = d['a'] + 5
d['b'] = d['a'] * 2
print(sum(d.values()))
Output
18
  • d['a'] becomes 6, d['b'] 12.
  • 6 + 12.
  • Answer: 18
Revision overview
Changed[k] = v
Update or add
ChangingPart 7
Removepop(k): the value
popitem(): last pair
clear(), del
Missingpop(k, default)
del name: NameError later
Revision: changing and removing dictionary items
Next · DictionariesDictionary Methods and Operations
05
Dictionaries

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

Python
marks = {}.fromkeys(['Math', 'English', 'Science'], 0)
print(marks)
for item in marks.items():
    print(item)
print(list(sorted(marks.keys())))
Output
{'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:

Python
d = dict.fromkeys(['a', 'b'], [])
d['a'].append(1)
print(d)
Output
{'a': [1], 'b': [1]}

5.2keys, values, setdefault, update, copy

Python
d = {'x': 10, 'y': 20, 'z': 30}
print(d.keys())
print(d.values())
print(list(d.keys()), sum(d.values()))
Output
dict_keys(['x', 'y', 'z'])
dict_values([10, 20, 30])
['x', 'y', 'z'] 60

keys() and values() give views; wrap them in list() to get a list, or use them directly in loops and with sum, len, in.

Python
d = {'a': 1}
print(d.setdefault('a', 100))
print(d.setdefault('b', 100))
print(d)
Output
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.

Python
d = {'a': 1, 'b': 2}
d.update({'b': 20, 'c': 3})
print(d)
Output
{'a': 1, 'b': 20, 'c': 3}

update() overwrites existing keys and adds new ones. copy() makes a new dictionary, unlike plain assignment:

Python
d = {'a': 1}
alias = d
c = d.copy()
d['b'] = 2
print(alias)
print(c)
Output
{'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.

Python
squares = {1: 1, 2: 4, 4: 16}
print(1 in squares)
print(16 in squares)
print(16 in squares.values())
Output
True
False
True
keysvalues11244161 in squares → True16 in squares → False16 in squares.values() → True
Figure 7. in looks at the keys; use .values() to search the values
Python
squares = {1: 1, 3: 9, 5: 25, 7: 49}
for i in squares:
    print(squares[i])
Output
1
9
25
49

To get each key with its value, loop over items() and unpack the pairs (extra):

Python
squares = {1: 1, 3: 9, 5: 25}
for k, v in squares.items():
    print(k, "->", v)
Output
1 -> 1
3 -> 9
5 -> 25

Adding or removing keys while looping over the same dictionary is not allowed (extra):

Python
d = {1: 1, 2: 4}
for k in d:
    d[k + 10] = 0
Error
RuntimeError: dictionary changed size during iteration

Loop over list(d) instead if keys must be added or removed inside the loop.

5.4Sorting by key or by value (extra)

Python
d = {'b': 2, 'c': 1, 'a': 3}
print(sorted(d))
print(sorted(d.items()))
print(sorted(d, key=d.get))
Output
['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

Exam tips
  • in on a dictionary: keys only.
  • Counting words: d[w] = d.get(w, 0) + 1.
Common mistakes
  • Expecting 16 in squares to find a value.
  • Sharing one list through fromkeys.
  • Changing the size of a dictionary inside a loop over it.

Practice questions (graded-assignment style)

Q1in on a dictionary

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
d = {1: 10, 2: 20}
print(10 in d, 2 in d)
1
True True
2
False True
3
True False
4
False False
Solution
Idea

Keys only.

Python
d = {1: 10, 2: 20}
print(10 in d, 2 in d)
Output
False True
  • 10 is a value, 2 is a key.
  • Answer: option 2.
Q2fromkeys and update

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
d = {}.fromkeys('ab', 0)
d.update({'b': 5, 'c': 7})
print(d)
1
{'ab': 0, 'b': 5, 'c': 7}
2
{'a': 0, 'b': 0, 'c': 7}
3
{'b': 5, 'c': 7}
4
{'a': 0, 'b': 5, 'c': 7}
Solution
Idea

fromkeys of a string uses its characters.

Python
d = {}.fromkeys('ab', 0)
d.update({'b': 5, 'c': 7})
print(d)
Output
{'a': 0, 'b': 5, 'c': 7}
  • Start {'a': 0, 'b': 0}; update changes b and adds c.
  • Answer: option 4.
Q3setdefault

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
d = {'a': 1}
d.setdefault('a', 9)
d.setdefault('b', 9)
print(d)
1
{'a': 1, 'b': 9}
2
{'a': 9, 'b': 9}
3
{'a': 1}
4
{'b': 9}
Solution
Idea

setdefault never overwrites.

Python
d = {'a': 1}
d.setdefault('a', 9)
d.setdefault('b', 9)
print(d)
Output
{'a': 1, 'b': 9}
  • 'a' exists and stays 1; 'b' is added with 9.
  • Answer: option 1.
Q4Counting

Numerical Answer Type (NAT).

What does the program print?

Python
words = ['x', 'y', 'x', 'x']
c = {}
for w in words:
    c[w] = c.get(w, 0) + 1
print(c['x'] - c['y'])
Solution
Idea

Count each word.

Python
words = ['x', 'y', 'x', 'x']
c = {}
for w in words:
    c[w] = c.get(w, 0) + 1
print(c['x'] - c['y'])
Output
2
  • x appears 3 times, y once.
  • Answer: 2
Revision overview
Buildingfromkeys(keys, v)
setdefault(k, v)
update(other)
Readingitems(), keys(), values()
in: keys only
MethodsPart 8
Loopingfor k in d
for k, v in d.items()
No size change inside
Sortingsorted(d): keys
sorted(d, key=d.get)
Revision: the dictionary methods and how to loop
Next · PracticeTry It Yourself
06
Practice

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.

Task 1Sets

Create two sets of numbers and print their union, intersection and difference.

Solution
Python
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print(A | B)
print(A & B)
print(A - B)
Output
{1, 2, 3, 4, 5, 6}
{3, 4}
{1, 2}
Task 2discard vs remove

Show what happens when discard() and remove() are both called on an element that is not in the set.

Solution
Python
s = {1, 2, 3}
s.discard(10)
print(s)
Output
{1, 2, 3}
Python
s = {1, 2, 3}
s.remove(10)
Error
KeyError: 10

discard quietly does nothing; remove raises KeyError.

Task 3Set from a list

Convert a list with duplicate values into a set, and explain what happens to the duplicates.

Solution
Python
nums = [1, 2, 2, 3, 3, 3]
unique = set(nums)
print(unique)
Output
{1, 2, 3}

Each value is kept once; the order of the list is not kept.

Task 4Dictionary basics

Build a dictionary of 3 students and their marks, then update one mark and add a new student.

Solution
Python
marks = {'Asha': 88, 'Rahul': 76, 'Mei': 91}
marks['Rahul'] = 80
marks['Zara'] = 85
print(marks)
Output
{'Asha': 88, 'Rahul': 80, 'Mei': 91, 'Zara': 85}

Rahul is updated in place; Zara is added at the end (insertion order).

Task 5get() vs []

Look up a missing key with both get() and [], and explain the difference in behaviour.

Solution
Python
d = {'a': 1}
print(d.get('b'))
Output
None
Python
d = {'a': 1}
print(d['b'])
Error
KeyError: 'b'

get returns None; [] raises KeyError.

Task 6Iterating a dictionary

Iterate over a dictionary's items() and print each key alongside its value doubled.

Solution
Python
scores = {'x': 10, 'y': 20}
for k, v in scores.items():
    print(k, v * 2)
Output
x 20
y 40
Task 7Mixed

Given a list of words, build a dictionary counting how many times each word appears.

Solution
Python
words = ['cat', 'dog', 'cat', 'bird', 'dog', 'cat']
counts = {}
for w in words:
    counts[w] = counts.get(w, 0) + 1
print(counts)
Output
{'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.

Next · All partsWeek 7 Summary Sheet
07
All parts

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

PropertyDictionarySet
Notation{'K': 'V'}{1, 2}
Creationdict()set()
MutabilityMutableMutable
Elements storedKeys: hashable · Values: anyHashable
OrderInsertion order (3.7+)Unordered
DuplicatesKeys: no · Values: yesNot allowed
OperationsKeys: add/delete · Values: add/update/deleteAdd, delete
Indexing / slicingNo positions; access by keyNo; iteration only
Sortingsorted(d) gives sorted keyssorted(s) gives a list
Empty{}set()

7.2Methods side by side

Dictionary methodsSet 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

Remove duplicates
Through a set
main.py
unique = set(items)

Use whenYou only care which values occur, not how often or in what order.

  1. set(items) keeps each value once.
  2. Use sorted(...) for a stable order.
  3. Use len(...) to count distinct values.
ExampleDistinct marks.
main.py
marks = [70, 85, 70, 92, 85]
print(sorted(set(marks)), len(set(marks)))
Output
[70, 85, 92] 3
Common and different items
Set algebra
main.py
both = A & B
only_A = A - B
either = A | B

Use whenComparing two groups.

  1. Turn the lists into sets.
  2. & for common, - for only in the first, | for all.
  3. ^ for in exactly one.
ExampleCourses two students share.
main.py
a = {"CT", "Maths", "Stats"}
b = {"CT", "Python"}
print(a & b, len(a | b))
Output
{'CT'} 4
Safe lookup
get with a default
main.py
value = d.get(key, default)

Use whenThe key might be missing and an error would be wrong.

  1. d[k] when the key must exist.
  2. d.get(k) for None if missing.
  3. d.get(k, v) for your own default.
ExampleA missing student.
main.py
marks = {"Asha": 88}
print(marks.get("Ravi", "absent"))
Output
absent
Count occurrences
The accumulator
main.py
counts[w] = counts.get(w, 0) + 1

Use whenCounting how often each value appears.

  1. Start with counts = {}.
  2. For each item add 1 to counts.get(item, 0).
  3. Read the counts with items().
ExampleLetters of a word.
main.py
counts = {}
for ch in "banana":
    counts[ch] = counts.get(ch, 0) + 1
print(counts)
Output
{'b': 1, 'a': 3, 'n': 2}
Loop over pairs
items()
main.py
for k, v in d.items():
    ...

Use whenYou need both the key and the value.

  1. items() gives (key, value) pairs.
  2. Unpack them in the for line.
  3. Do not add or remove keys inside the loop.
ExampleMarks with a bonus.
main.py
d = {"a": 10, "b": 20}
for k, v in d.items():
    print(k, v + 5)
Output
a 15
b 25
Remove from a dictionary
By key, or the last pair
main.py
v = d.pop(k)
k, v = d.popitem()

Use whenYou need the removed value, or to undo the last addition.

  1. pop(k) returns the value.
  2. popitem() takes the last pair added.
  3. del d[k] just deletes.
ExampleUndo the last insertion.
main.py
d = {"x": 1}
d["y"] = 2
print(d.popitem(), d)
Output
('y', 2) {'x': 1}

7.3Common errors to avoid

MistakeWhat Python says
{1, 2, [3, 4]}TypeError: cannot use 'list' as a set element (unhashable type: 'list')
s[0] on a setTypeError: 'set' object is not subscriptable
s.remove(2), 2 not in sKeyError: 2
set().pop()KeyError: 'pop from an empty set'
d['address'], missing keyKeyError: 'address'
a list as a keyTypeError: cannot use 'list' as a dict key (unhashable type: 'list')
printing after del squaresNameError: name 'squares' is not defined
adding keys while loopingRuntimeError: dictionary changed size during iteration
MistakeCorrect idea
{} for an empty set{} is a dict; use set().
popitem() is randomIt removes the last pair added (Python 3.7+).
16 in squares to find a valuein checks keys; use 16 in squares.values().
dict.fromkeys(keys, [])All keys share one list.
Expecting a fixed set orderSets have none; print through sorted().

7.4Last-minute checklist

  • Set notation, uniqueness, and why {} makes a dict, not a set
  • add() vs update(), and discard() vs remove()
  • Set operations: union, intersection, difference and their operators
  • Dictionary key: value pairs, and the key immutability and uniqueness rules
  • get() vs [] for missing keys
  • pop(), popitem(), clear() and del on dictionaries
  • Membership test (in) checks keys only, never values
  • Dictionary methods: fromkeys(), items(), keys(), sorted()
  • The full property comparison: dictionary vs set
Revision overview
Sets{ }, set()
Unique, unordered
add, update
Set operationsdiscard vs remove
| & - ^
subset, superset
Week 7Sets and dictionaries
Dictionarieskey: value
[] vs get()
Insertion order
Changingd[k] = v
pop, popitem (last)
clear, del
Methodsitems, keys, values
in: keys only
get(w, 0) + 1
Revision: all of Week 7 on one page
Back to top