←
Class 11 Computer Science
10. Tuples and dictionaries in Python · 10 / 11
⌕
Chapter 10 of 11

10. Tuples and dictionaries in Python

15 sections · 7,539 words

About this chapter

226 words · 1 min read

Big idea: A tuple is a frozen row of values. A dictionary is a labelled lookup table.

This is an original lesson that follows the Class 11 Computer Science syllabus. Read the key words first. Cover a worked answer and try the steps yourself before you look. For a program, say what it will print before you read the real output.

  • Create tuples, including a one-value tuple that needs a comma.
  • Read tuple values with indexes and slices, and show why a tuple cannot be changed.
  • Join, repeat, search and slice tuples, and use count, index, len, min, max and sum.
  • Unpack tuples, swap two variables, nest tuples, and write small tuple programs.
  • Create dictionaries, read values by key, add and change items, and test membership on keys.
  • Walk a dictionary by keys, values and items, and use get, update, del and related methods.
  • Build useful dictionaries, including letter counts and digit-to-word maps.

Python first appeared in 1991, created by Guido van Rossum. From the start it offered tuples as frozen sequences and dictionaries as hash maps. A hash map finds a value from a key without walking every item. Later Python versions kept dictionary items in the order they were first inserted. A mapping still comes back in the order you typed. Keys stay unique and immutable.

10.1 Introduction to tuples

894 words · 4 min read

A tuple is an ordered row. You must not change it later.

A tuple is an ordered sequence.

Ordered means each value has a fixed place.

That place is an index.

The first place is index 0.

You write a tuple in parentheses.

Parentheses are round brackets.

Values are separated by commas.

Values may have different data types.

A number, text, list, or another tuple can sit in one row.

A list is also ordered. You may change a list.

A tuple is immutable.

Immutable means the row itself cannot be edited later.

People often store mixed facts in a tuple.

A seat number, a label and a score can sit together.

  • Tuple: an ordered row of values in parentheses that you cannot change.
  • Index: the place number of a value, starting at 0.
  • Immutable: cannot be changed after it is created.
  • Parentheses: round brackets, used to write a tuple.
FeatureTupleList
Brackets( )[ ]
Can you change an item?NoYes
Grow in place?No. Build a new tuple.Yes. append and friends.
Typical useA frozen recordA changing collection

How to read the table. Compare one row at a time. The first column names the feature. The next two columns show the two types.

Here are four tuples.

One holds only integers.

One mixes types.

One holds a list.

One holds a smaller tuple.

Python
>>> (3, 6, 9, 12, 15)
(3, 6, 9, 12, 15)
>>> ("maths", 88, "science", 91.5)
('maths', 88, 'science', 91.5)
>>> (10, 20, 30, [40, 50])
(10, 20, 30, [40, 50])
>>> (1, 2, 3, (10, 20))
(1, 2, 3, (10, 20))

Parentheses alone do not make a tuple.

The comma does.

If you write only (20), Python treats it as the integer 20.

Write (20,) with a comma to make a one-value tuple.

A comma-separated row without parentheses is also a tuple.

Python
print(type((20)))
print((20))
print(type((20,)))
print((20,))
seq = 1, 2, 3
print(type(seq))
print(seq)

Output
<class 'int'>
20
<class 'tuple'>
(20,)
<class 'tuple'>
(1, 2, 3)

If you forget the comma, len((20)) fails.

Python tries to take the length of the integer 20.

The error type is TypeError.

Python
n = (20)
try:
    print(len(n))
except TypeError as err:
    print(type(err).__name__)

Output
TypeError
Remember the comma, not just the brackets. (20,) is a tuple. (20) is not.

You read one value with square brackets.

Lists and strings use the same idea.

You may use a positive index.

You may use a negative index.

You may use a small sum that makes an integer index.

Index 0 is the left end.

Index −1-1 is the right end.

(8)(5)(9)(2)(7)(4)012345-6-5-4-3-2-1
A tuple is an ordered row. Index 0 is first. Index -1 is last.

How to read the figure. The top numbers are indexes from the left. The bottom numbers are indexes from the right. The same box has two names.

Python
pack = (2, 4, 6, 8, 10, 12)
print(pack[0])
print(pack[3])
print(pack[1 + 4])
print(pack[-1])

Output
2
8
12
12

An index past the end is not allowed.

Python raises IndexError.

Python
pack = (2, 4, 6, 8, 10, 12)
try:
    print(pack[15])
except IndexError as err:
    print(type(err).__name__)

Output
IndexError

You cannot replace a value inside a tuple.

An attempt raises TypeError.

The row is frozen. That is useful.

If the data must not change by accident, store it in a tuple.

Python
pack = (1, 2, 3, 4, 5)
try:
    pack[4] = 10
except TypeError as err:
    print(type(err).__name__)

Output
TypeError

There is one twist.

A tuple may hold a mutable value, such as a list.

Mutable means you can change it.

You still cannot replace that list with a different object.

You can change values inside the list.

Python
mix = (1, 2, 3, [8, 9])
mix[3][1] = 10
print(mix)

Output
(1, 2, 3, [8, 10])

The comma makes a one-value tuple, not the parentheses.

Write a one-value tuple that holds 20, then say what (20) is.

Goal. Tell a one-value tuple from a plain integer.

Rule. A one-value tuple needs a comma.

Look. (20) has no comma, so it is the integer 20.

Look. (20,) has a comma, so it is a tuple of length 1.

Result: (20,) is the tuple. (20) is the integer 20.

Think of a tuple as a sealed box. You can look inside. You cannot swap the items unless a box inside is itself open, like a list.

Cover the answers. Try each item on paper first.

Watch out: A pair of parentheses around one number does not make a tuple. You need the comma: (20,).

⚡ Quick Check Flashcards4 questions
Question 1
What index does the first value in a tuple use?
Try answering before revealing!
Question 2
How do you write a tuple that holds only the number 7?
Try answering before revealing!
Question 3
Can you replace pack[0] on a tuple of numbers?
Try answering before revealing!
Question 4
A tuple holds a list. Can you change a value inside that list?
Try answering before revealing!

10.2 Tuple operations

691 words · 3 min read

You can join tuples, repeat them, test membership, and cut slices. None of these edits the old tuple in place.

A tuple does not grow by editing.

Operators build a new tuple from old ones.

The old tuples stay as they were.

  • Concatenation: joining two tuples end to end with +.
  • Repetition: copying a tuple several times with *.
  • Slice: a cut of a sequence, written start:stop.
  • Step: how many places to jump in a slice.

Concatenation means joining two sequences end to end.

The operator is +.

Both sides must be tuples.

The result is a new tuple.

You may store that new tuple in a name, even the old name.

That does not change the old object.

It points the name at a new object.

Python
left = (1, 3, 5, 7, 9)
right = (2, 4, 6, 8, 10)
print(left + right)
colours = ('red', 'green', 'blue')
more = ('cyan', 'yellow')
joined = colours + more
print(joined)
row = (1, 2, 3, 4, 5)
row = row + (6,)
print(row)
row = row + (7, 8, 9)
print(row)

Output
(1, 3, 5, 7, 9, 2, 4, 6, 8, 10)
('red', 'green', 'blue', 'cyan', 'yellow')
(1, 2, 3, 4, 5, 6)
(1, 2, 3, 4, 5, 6, 7, 8, 9)

Repetition copies a tuple several times.

The operator is *.

One side is a tuple.

The other side must be an integer.

The result is a new tuple.

Python
print(('hello', 'world') * 3)
print(('hello',) * 4)

Output
('hello', 'world', 'hello', 'world', 'hello', 'world')
('hello', 'hello', 'hello', 'hello')

The operator in asks whether a value sits in the tuple.

It answers True or False.

The operator not in asks the opposite question.

Python
flags = ('red', 'green', 'blue')
print('green' in flags)
print('green' not in flags)
print('yellow' in flags)

Output
True
False
False

A slice is a cut of a sequence.

You write tuple[start:stop].

Python includes start.

It does not include stop.

Miss out start and the cut begins at 0.

Miss out stop and the cut runs to the end.

A third number is the step.

Step 2 means every second value.

Step −1-1 walks the tuple backwards.

Python
line = (10, 20, 30, 40, 50, 60, 70, 80)
print(line[2:7])
print(line[0:len(line)])
print(line[:5])
print(line[2:])
print(line[0:len(line):2])
print(line[-6:-4])
print(line[::-1])

Output
(30, 40, 50, 60, 70)
(10, 20, 30, 40, 50, 60, 70, 80)
(10, 20, 30, 40, 50)
(30, 40, 50, 60, 70, 80)
(10, 30, 50, 70)
(30, 40)
(80, 70, 60, 50, 40, 30, 20, 10)

The slice line[2:7] keeps indexes 2, 3, 4, 5 and 6.

That is 7−2=57-2=5 values.

A step of 2 on a tuple of length 6 keeps 3 values.

Start with two tuplesJoin with + or repeat with *Or cut a sliceA brand new tuple is the result
Tuple operators build a new tuple. They do not edit the old one.

How to read the figure. Start at the top. Each arrow is a new object. The old tuples stay in memory unless you drop the name.

+ and * never edit a tuple in place.

What is (10, 20, 30, 40, 50, 60, 70, 80)[2:7]?

Goal. Cut a slice and list the kept values.

Rule. Keep start. Drop stop.

Start. Index 2 is 30.

Stop. Index 7 is 80, so 80 is not kept.

Keep. 30, 40, 50, 60, 70.

Result: (30, 40, 50, 60, 70)

Pause here. Answer before you scroll to the answers.

Watch out: Joining with + does not stretch the old tuple. It builds a new tuple. The old one is unchanged unless you store the new one in the same name.

⚡ Quick Check Flashcards4 questions
Question 1
What does (1, 2) + (3,) print?
Try answering before revealing!
Question 2
What type must the right-hand side of tuple * n be?
Try answering before revealing!
Question 3
Does "green" in ("red", "green") look at values or indexes?
Try answering before revealing!
Question 4
What does line[::-1] do?
Try answering before revealing!

10.3 Tuple methods and built-in functions

459 words · 2 min read

Python gives a short toolkit for counting, searching, measuring and sorting tuple values.

A method is a function that belongs to an object.

You write it after a dot.

A built-in function is a function Python already knows, such as len.

Tuples support only a few methods, because you cannot edit them.

You cannot append.

You cannot remove.

  • Method: a function you call on an object with a dot.
  • Built-in function: a function Python provides, such as len, min, max and sum.
ToolWhat it does
len(t)How many values t holds.
tuple(seq)Build a tuple from a sequence, or an empty tuple if you pass nothing.
t.count(x)How many times x appears in t.
t.index(x)The index of the first x. Missing x is an error.
sorted(t)A new sorted list. The tuple itself does not change.
min(t)The smallest value.
max(t)The largest value.
sum(t)The total of numeric values.

How to read the table. The left column is the call. The right column is the job. Notice that none of these rewrite the tuple in place.

Python
pack = (4, 11, 6, 11, 9)
print(len(pack))
print(pack.count(11))
print(pack.count(90))
print(pack.index(6))
print(min(pack))
print(max(pack))
print(sum(pack))
print(sorted(pack))
print(pack)
print(tuple())
print(tuple('aeiou'))
print(tuple([1, 2, 3]))
print(tuple(range(5)))

Output
5
2
0
2
4
11
41
[4, 6, 9, 11, 11]
(4, 11, 6, 11, 9)
()
('a', 'e', 'i', 'o', 'u')
(1, 2, 3)
(0, 1, 2, 3, 4)

The pack is (4, 11, 6, 11, 9).

Its length is 5.

The value 11 appears twice.

The sum is 4+11+6+11+9=414+11+6+11+9=41.

sorted returns a list, not a tuple.

The original pack is still unsorted.

If the value is not in the tuple, index raises ValueError.

Python
pack = (10, 20, 30, 40, 50)
print(pack.index(30))
try:
    print(pack.index(90))
except ValueError as err:
    print(type(err).__name__)

Output
2
ValueError
count of a missing value is 0. index of a missing value is an error.

sorted(t) returns a list. The tuple stays in the old order.

For pack = (4, 11, 6, 11, 9), find len, min, max and sum.

Goal. Measure the five numbers.

Count. There are five values.

Compare. The smallest is 4. The largest is 11.

Add. 4+11=154+11=15, then +6=21+6=21, then +11=32+11=32, then +9=41+9=41.

Result: len is 5, min is 4, max is 11, sum is 41.

Write a short answer. Then check the notes below.

Watch out: sorted(t) does not sort the tuple. It returns a new list. The tuple stays in the old order.

⚡ Quick Check Flashcards4 questions
Question 1
What does (4, 11, 6, 11, 9).count(11) print?
Try answering before revealing!
Question 2
What does tuple("cat") print?
Try answering before revealing!
Question 3
Does sorted change the tuple?
Try answering before revealing!
Question 4
What error does (1, 2).index(9) raise?
Try answering before revealing!

10.4 Tuple assignment

548 words · 2 min read

Python can unpack a tuple into several names in one line. That is how you swap two values.

Tuple assignment puts a tuple of names on the left of =.

It puts a tuple of values on the right.

Python copies each value to the matching name.

The counts on both sides must match.

Too few values, or too many, is an error.

  • Tuple assignment: giving several names their values from one tuple in one step.
  • Unpack: split a tuple into separate names.
  • Pack: join several values into one tuple.
Python
num1, num2 = (10, 20)
print(num1)
print(num2)
record = ('Student A', 40, 'CS')
name, seat, subject = record
print(name)
print(seat)
print(subject)

Output
10
20
Student A
40
CS

The parentheses on the left are optional.

num1, num2 = 10, 20 is the same idea.

If the right-hand side is an expression, Python works it out first, then unpacks.

Python
num3, num4 = (10 + 5, 20 + 5)
print(num3)
print(num4)

Output
15
25

Four names and three values do not match.

Python raises ValueError.

Python
try:
    a, b, c, d = (5, 6, 8)
except ValueError as err:
    print(type(err).__name__)

Output
ValueError

A swap exchanges two values.

In some languages you need a spare box.

In Python you unpack.

The line a, b = b, a packs the right side first.

Then it unpacks into the names on the left.

174(17, 4)pack(17, 4)a = 17b = 4unpackSwap: a, b = b, a
Packing builds one tuple. Unpacking splits it into names.

How to read the figure. The top arrow packs two values into one pair. The bottom arrow unpacks that pair into two names. Swap packs the old values in reverse order, then unpacks.

After a, b = b, a, aa holds the old bb, which was 4.

Then bb holds the old aa, which was 17.

The sum is still 21.

Python
a = 17
b = 4
print(a, b)
a, b = b, a
print(a, b)

Output
17 4
4 17

Python packs the right side first. Then it unpacks to the left.

Trace the swap. Start with a = 17 and b = 4. What are a and b after a, b = b, a?

Goal. Follow each step of the swap.

Start. a is 17. b is 4.

Pack. The right side becomes the pair (4, 17).

Unpack. The left names take those values in order.

a. The first name a becomes 4.

b. The second name b becomes 17.

Check. 4+17=214+17=21, same as 17+417+4.

Result: a is 4 and b is 17.

Say the result out loud. Then read the answers.

Watch out: The number of names on the left must equal the number of values on the right. A mismatch is ValueError, not TypeError.

⚡ Quick Check Flashcards4 questions
Question 1
What does this set n to? n, m = (9, 4)
Try answering before revealing!
Question 2
How do you swap a and b in one line?
Try answering before revealing!
Question 3
Why does a, b, c = (1, 2) fail?
Try answering before revealing!
Question 4
Does the right-hand side get worked out before the names change?
Try answering before revealing!

10.5 Nested tuples

399 words · 2 min read

A nested tuple is a tuple that holds other tuples. That is a neat way to store several records.

A nested tuple is a tuple inside another tuple.

Each inner tuple can be one record.

A record might be a seat number, a label and a mark.

The outer tuple is then the whole class list.

You read one field with two indexes.

First pick which record.

Then pick which field.

  • Nested tuple: a tuple that contains other tuples.
  • Record: a group of related facts stored together.
0: (201, Student A, 88)1: (202, Student B, 91)2: (203, Student C, 76)
Nested tuples. Outer index picks the record. Inner index picks a field.

How to read the figure. Each row is one inner tuple. The number on the left is the outer index. group[1][2] is row 1, field 2, which is 91.

Python
group = (
    (201, 'Student A', 88),
    (202, 'Student B', 91),
    (203, 'Student C', 76),
)
print('No', 'Seat', 'Label', 'Mark')
for i in range(len(group)):
    row = group[i]
    print(i + 1, row[0], row[1], row[2])
print(group[1][2])

Output
No Seat Label Mark
1 201 Student A 88
2 202 Student B 91
3 203 Student C 76
91

Student B is at outer index 1.

The mark is at inner index 2, so group[1][2] is 91.

The three marks add to 255.

Their mean is 85.

The print uses a loop.

A loop repeats a step.

range(len(group)) walks 0, 1, 2.

The escape \t in other programs means a tab. The escape \n means a new line. This program uses plain spaces.

From group above, what is group[2][0]?

Goal. Read one field from a nested tuple.

Outer. Index 2 is the third record.

Inner. Index 0 is the seat number.

Read. That record starts with 203.

Result: 203

Predict first. Then compare with the notes.

Watch out: group[1][2] is not the same as group[2][1]. The first index picks the inner tuple. The second index picks a field inside it.

⚡ Quick Check Flashcards4 questions
Question 1
What is a nested tuple?
Try answering before revealing!
Question 2
How do you read the mark of the first record in group?
Try answering before revealing!
Question 3
How many inner tuples are in group in the program?
Try answering before revealing!
Question 4
Why use a tuple for each record?
Try answering before revealing!

10.6 Tuple handling

564 words · 3 min read

Small programs show three everyday jobs: swap, return two results, and summarise a frozen row of numbers.

You now put the ideas to work.

Programs here do not wait for typing.

They use ready values so you can see the exact printout.

The same steps work if a later program reads input.

Store two numbers. Print them.

Unpack them the other way round. Print them again.

No spare name is needed.

Python
num1 = 5
num2 = 10
print('before', num1, num2)
num1, num2 = num2, num1
print('after', num1, num2)

Output
before 5 10
after 10 5

A function is a named bundle of steps.

A function may return a tuple.

The caller unpacks that tuple.

Here a function finds the area and the perimeter of a rectangle of width 5 and height 4.

Area is 5×4=205 \times 4 = 20.

Perimeter is 2×(5+4)=182\times(5+4)=18.

Python
def box(w, h):
    area = w * h
    perimeter = 2 * (w + h)
    return (area, perimeter)

area, perimeter = box(5, 4)
print(area)
print(perimeter)

Output
20
18

Start with an empty tuple tuple().

Add one number at a time with concatenation.

Then use max and min.

Adding (num,) is required.

If you add num without a comma, you are not adding a tuple.

Python
numbers = tuple()
for num in (9, 8, 10, 12, 15):
    numbers = numbers + (num,)
print(numbers)
print(max(numbers))
print(min(numbers))

Output
(9, 8, 10, 12, 15)
15
8

A string method split cuts text at a mark.

Each address has a user part, then @, then a domain part.

Store the three tuples: the full addresses, the users, and the domains.

Python
mails = ('[email protected]', '[email protected]', '[email protected]')
users = tuple()
domains = tuple()
for item in mails:
    user, domain = item.split('@')
    users = users + (user,)
    domains = domains + (domain,)
print(mails)
print(users)
print(domains)

Output
('[email protected]', '[email protected]', '[email protected]')
('a', 'b', 'c')
('school.net', 'club.org', 'school.net')

Membership with in is the built-in test.

You can also write a small function that walks the tuple yourself.

Both answers must match.

Python
labels = ('Player 1', 'Player 2', 'Player 3')

def present(row, target):
    for item in row:
        if item == target:
            return True
    return False

print(present(labels, 'Player 2'))
print('Player 2' in labels)
print(present(labels, 'Player 9'))
print('Player 9' in labels)

Output
True
True
False
False

When you grow a tuple in a loop, add (num,) with the comma.

A function returns (20, 18). How do you store both numbers in area and edge?

Goal. Unpack two returned values.

Rule. Put names on the left. Put the call on the right.

Write. area, edge = box(5, 4).

Check. Area should be 20. Perimeter should be 18.

Result: area, edge = box(5, 4) stores 20 and 18.

Check these without looking back. Then read the notes.

Watch out: When you grow a tuple in a loop, add (num,) with the comma. Adding a plain integer with + is a TypeError.

⚡ Quick Check Flashcards4 questions
Question 1
What does a, b = box(5, 4) store if box returns (20, 18)?
Try answering before revealing!
Question 2
Why write numbers = numbers + (num,)?
Try answering before revealing!
Question 3
What built-ins find the largest and smallest of a numeric tuple?
Try answering before revealing!
Question 4
How can you split "[email protected]" into user and domain?
Try answering before revealing!

10.7 Introduction to dictionaries

497 words · 2 min read

A dictionary maps each key to a value. You look things up by name instead of by place.

A dictionary is a mapping.

A mapping pairs each key with one value.

One pair is an item.

You write an item as key: value.

Items go inside curly braces { }.

Consecutive items are separated by commas.

In current Python, items keep the order you first put them in.

Keys must be unique.

Two items cannot share a key.

Keys must be immutable: a number, a string, or a tuple of immutable values.

Values may repeat.

Values may be any type.

  • Dictionary: a mapping from unique keys to values, written in curly braces.
  • Key: the label you look up.
  • Value: the data stored under that key.
  • Item: one key-value pair.
pensclipsglue1274
A dictionary maps each key to one value. You look up the key, not a place.

How to read the figure. Each left box is a key. Follow the arrow. The right box is the value for that key. There is no index 0 here.

Empty curly braces make an empty dictionary.

The built-in dict() also makes an empty one.

Then you fill it with items.

Python
d1 = {}
print(d1)
d2 = dict()
print(d2)
marks = {'Student A': 95, 'Student B': 89, 'Student C': 92, 'Student D': 85}
print(marks)
pairs = [('Student A', 95), ('Student B', 89)]
print(dict(pairs))

Output
{}
{}
{'Student A': 95, 'Student B': 89, 'Student C': 92, 'Student D': 85}
{'Student A': 95, 'Student B': 89}

You do not use a position.

You use the key in square brackets.

The key Student B always maps to 89 in the next program, wherever that item sits.

A missing key raises KeyError.

Python
marks = {'Student A': 95, 'Student B': 89, 'Student C': 92, 'Student D': 85}
print(marks['Student B'])
print(marks['Student D'])
try:
    print(marks['Student Z'])
except KeyError as err:
    print(type(err).__name__)

Output
89
85
KeyError

Square brackets on a dictionary need a key, not an index.

In marks above, what does marks["Student A"] return?

Goal. Look up one value by key.

Rule. Use the key, not a place number.

Find. Student A maps to 95.

Result: 95

A tuple is a row of locked boxes numbered 0, 1, 2. A dictionary is a row of labelled drawers. You pull the drawer by its label.

Cover the answers. Try each item on paper first.

Watch out: Square brackets on a dictionary need a key, not an index. marks[0] is wrong unless 0 is actually a key.

⚡ Quick Check Flashcards4 questions
Question 1
What symbols wrap a dictionary?
Try answering before revealing!
Question 2
Must keys be unique?
Try answering before revealing!
Question 3
What error does a missing key raise with square brackets?
Try answering before revealing!
Question 4
Can a list be a key?
Try answering before revealing!

10.8 Dictionaries are mutable

403 words · 2 min read

You may add a new item or overwrite an old value after the dictionary already exists.

Dictionaries are mutable.

You may change the contents after creation.

Adding uses a new key.

Changing uses an old key.

Both use the same writing: d[key] = value.

If the key is new, Python adds an item.

If the key is old, Python replaces the value.

Python
marks = {'Student A': 95, 'Student B': 89, 'Student C': 92, 'Student D': 85}
marks['Student E'] = 78
print(marks)
marks['Student C'] = 93.5
print(marks)

Output
{'Student A': 95, 'Student B': 89, 'Student C': 92, 'Student D': 85, 'Student E': 78}
{'Student A': 95, 'Student B': 89, 'Student C': 93.5, 'Student D': 85, 'Student E': 78}

Student E was not there, so that line added an item.

Student C was there, so that line changed 92 into 93.5.

The other items stayed.

This is the opposite of a tuple, where item assignment is TypeError.

A value may itself be a dictionary.

That is a nested dictionary.

The outer key picks an inner map.

Then an inner key picks a value.

Python
week = {
    'Mon': {'am': 'maths', 'pm': 'games'},
    'Tue': {'am': 'science', 'pm': 'art'},
}
print(week['Mon']['pm'])
week['Tue']['am'] = 'music'
print(week['Tue'])

Output
games
{'am': 'music', 'pm': 'art'}

==d[key] = value adds when the key is new and overwrites when the key already exists.==

Trace bag line by line. Start with bag = {"pens": 12}. Add clips mapped to 7. Then change pens to 15. What is bag after each line?

Goal. Show the dictionary after every assignment.

Rule. A new key adds. An old key overwrites.

Line 1. bag is {pens: 12}.

Line 2. clips is new, so bag becomes {pens: 12, clips: 7}. Two counts add to 19.

Line 3. pens is old, so 12 is replaced by 15.

Check. clips is still 7. Only pens changed.

Result: {green|{'pens': 15, 'clips': 7}}

Pause here. Answer before you scroll to the answers.

Watch out: d[key] = value adds when the key is new and overwrites when the key already exists. There is no separate add operator you must remember.

⚡ Quick Check Flashcards4 questions
Question 1
How do you add a new key "glue" with value 4 to bag?
Try answering before revealing!
Question 2
How do you change the value for "pens"?
Try answering before revealing!
Question 3
Are dictionaries immutable like tuples?
Try answering before revealing!
Question 4
What is week["Mon"]["pm"] if week nests two dictionaries as in the program?
Try answering before revealing!

10.9 Dictionary operations

323 words · 1 min read

The operators in and not in test keys, not values.

Membership on a dictionary asks about keys.

k in d is True when kk is a key.

It does not look at the values.

That surprises people who just stored those values.

If you need to know whether a value is present, walk d.values().

Python
marks = {'Student A': 95, 'Student B': 89, 'Student C': 92, 'Student D': 85}
print('Student C' in marks)
print('Student C' not in marks)
print(95 in marks)
print(95 in marks.values())

Output
True
False
False
True

Student C is a key, so the first test is True.

95 is a value, not a key, so 95 in marks is False.

95 in marks.values() is True.

Ask: is this a key?Yes: in is TrueNo: check values() if you meant a value
in on a dictionary tests keys first.

How to read the figure. Start with the key question. Only go to values() if that is what you meant.

in on a dictionary does not search the values.

For bag = {"pens": 12, "clips": 7}, is 12 in bag?

Goal. Decide what in tests.

Rule. in looks at keys.

Keys. The keys are pens and clips, not 12.

Value test. Use 12 in bag.values() if you mean the number.

Result: False, because 12 is a value.

Write a short answer. Then check the notes below.

Watch out: in on a dictionary does not search the values. "95 in marks" is False even when someone scored 95.

⚡ Quick Check Flashcards4 questions
Question 1
What does "Student C" in marks test?
Try answering before revealing!
Question 2
How do you test whether 95 is stored as a value?
Try answering before revealing!
Question 3
What does "Student Z" not in marks print if that key is missing?
Try answering before revealing!
Question 4
Why might 7 in {"clips": 7} be False?
Try answering before revealing!

10.10 Traversing a dictionary

369 words · 2 min read

A for loop can walk keys, values, or whole items.

To traverse means to visit each part in turn.

A for loop does that.

The plain loop for key in d walks keys.

Inside the loop you can still read d[key] to get the value.

A second style unpacks each item: for key, value in d.items().

  • Traverse: visit each item, usually with a loop.
Python
marks = {'Student A': 95, 'Student B': 89, 'Student C': 92, 'Student D': 85}
for key in marks:
    print(key, ':', marks[key])
print('---')
for value in marks.values():
    print(value)
print('---')
for key, value in marks.items():
    print(key, ':', value)

Output
Student A : 95
Student B : 89
Student C : 92
Student D : 85
---
95
89
92
85
---
Student A : 95
Student B : 89
Student C : 92
Student D : 85

All three walks see the same four items.

The first walk prints keys with values.

The second walk prints only values.

The third walk unpacks each pair.

Choose the walk that names what you need.

Take the dictionaryWalk keys, or values, or itemsUse each piece inside the loop
Three ways to traverse a dictionary.

How to read the figure. Pick one of the three walks. Then use that piece in the loop body. Do not mix them by accident.

for x in d gives keys, not values.

Write a loop that prints only the keys of bag.

Goal. Print each key and nothing else.

Rule. for key in bag walks keys.

Body. print(key) inside the loop.

Result: for key in bag: print(key)

Say the result out loud. Then read the answers.

Watch out: for x in d gives keys. If you print x and hoped to see values, you will see labels instead.

⚡ Quick Check Flashcards4 questions
Question 1
What does for k in d loop over?
Try answering before revealing!
Question 2
How do you loop over values only?
Try answering before revealing!
Question 3
How do you unpack keys and values together?
Try answering before revealing!
Question 4
Does the plain for loop need d.items()?
Try answering before revealing!

10.11 Dictionary methods and built-in functions

513 words · 2 min read

A small set of methods lets you list keys, fetch safely, merge, and delete.

These are the tools you will see in exams and in short programs.

len counts items.

dict can build a dictionary from pairs.

keys, values and items give views of those three parts.

A view is a live window onto the dictionary, not a frozen copy.

ToolWhat it does
len(d)How many items d holds.
dict(pairs)Build a dictionary from a sequence of (key, value) pairs.
d.keys()A view of the keys.
d.values()A view of the values.
d.items()A view of (key, value) tuples.
d.get(k)The value for k, or None if k is missing. No KeyError.
d.update(other)Add or overwrite items from other into d.
del d[k]Remove the item with key k.
del dRemove the whole dictionary name.
d.clear()Remove every item. The empty dictionary remains.

How to read the table. Find the job on the right. Then copy the call on the left. get is the safe lookup. del d[k] is the delete of one item.

Python
marks = {'Student A': 95, 'Student B': 89, 'Student C': 92, 'Student D': 85}
print(len(marks))
print(list(marks.keys()))
print(list(marks.values()))
print(list(marks.items()))
print(marks.get('Student D'))
print(marks.get('Student Z'))
extra = {'Student E': 79, 'Student F': 89}
marks.update(extra)
print(marks)
print(extra)
del marks['Student B']
print(marks)
marks.clear()
print(marks)

Output
4
['Student A', 'Student B', 'Student C', 'Student D']
[95, 89, 92, 85]
[('Student A', 95), ('Student B', 89), ('Student C', 92), ('Student D', 85)]
85
None
{'Student A': 95, 'Student B': 89, 'Student C': 92, 'Student D': 85, 'Student E': 79, 'Student F': 89}
{'Student E': 79, 'Student F': 89}
{'Student A': 95, 'Student C': 92, 'Student D': 85, 'Student E': 79, 'Student F': 89}
{}

get is the safe lookup.

A missing key returns None, which print shows as None.

Square brackets would have raised KeyError instead.

update copies items into the first dictionary.

The second dictionary is not emptied.

clear leaves {}.

del marks would then remove the name.

Using the name after that raises NameError.

Python
bag = {'pens': 12}
del bag
try:
    print(bag)
except NameError as err:
    print(type(err).__name__)

Output
NameError
get never raises KeyError for a missing key. Square brackets do.

Use get when the key might be absent.

What does {"a": 1, "b": 2}.get("c") print if you print it?

Goal. Predict a safe lookup.

Rule. get looks up the key. A miss returns None.

Look. c is not a key.

Result: None

Predict first. Then compare with the notes.

Watch out: get never raises KeyError for a missing key. Square brackets do. Use get when the key might be absent.

⚡ Quick Check Flashcards4 questions
Question 1
What does len({"a": 1, "b": 2}) print?
Try answering before revealing!
Question 2
How does get differ from square brackets?
Try answering before revealing!
Question 3
Does d.update(other) empty other?
Try answering before revealing!
Question 4
What is the difference between d.clear() and del d?
Try answering before revealing!

10.12 Manipulating dictionaries

890 words · 4 min read

Real jobs for a dictionary include labelled tables, stock lists, letter counts, and digit words.

Once you can add, fetch, walk and delete, you can build useful maps.

The next programs use ready data instead of typing, so the printout is fixed.

Keys are the odd numbers from 1 to 9.

Values are the matching words.

Then you list keys, values and items, take the length, test membership, fetch 9, and delete 9.

Python
odd = {1: 'one', 3: 'three', 5: 'five', 7: 'seven', 9: 'nine'}
print(odd)
print(list(odd.keys()))
print(list(odd.values()))
print(list(odd.items()))
print(len(odd))
print(7 in odd)
print(2 in odd)
print(odd.get(9))
del odd[9]
print(odd)

Output
{1: 'one', 3: 'three', 5: 'five', 7: 'seven', 9: 'nine'}
[1, 3, 5, 7, 9]
['one', 'three', 'five', 'seven', 'nine']
[(1, 'one'), (3, 'three'), (5, 'five'), (7, 'seven'), (9, 'nine')]
5
True
False
nine
{1: 'one', 3: 'three', 5: 'five', 7: 'seven'}

Each worker label maps to a whole number of hours.

Hours are not money. They are counts of time.

A loop prints each pair.

Python
staff = {'Worker A': 12, 'Worker B': 34, 'Worker C': 24, 'Worker D': 30, 'Worker E': 25}
print('label', 'hours')
for name in staff:
    print(name, staff[name])

Output
label hours
Worker A 12
Worker B 34
Worker C 24
Worker D 30
Worker E 25

A frequency is a count of how often something appears.

Walk each character.

If it is already a key, add one to its value.

If not, start that key at 1.

The word books has length 6.

The letter o appears twice.

The plot below is that model: one line of the four different letters b, o, k, s.

Python
text = 'books'
freq = {}
for ch in text:
    if ch in freq:
        freq[ch] += 1
    else:
        freq[ch] = 1
for key in freq:
    print(key, ':', freq[key])

Output
b : 1
o : 2
k : 1
s : 1
Model of letter counts in the word books. The four x positions are the four different letters in first-seen order: b, o, k, s.

How to read the figure. x = 1 is b, x = 2 is o, x = 3 is k, x = 4 is s. The height is the count. o and s both sit at 2.

Store a map from each digit 0 to 9 onto its word.

Read a number as text so you can walk each character.

Convert the character to an integer key.

Add the word to a result string.

For 6512 the digits add to 14, which is only a check that four digits were used.

The useful output is the words.

Python
def convert(num):
    names = {
        0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four',
        5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine',
    }
    result = ''
    for ch in num:
        result = result + ' ' + names[int(ch)]
    return result

num = '6512'
print(num)
print(convert(num).strip())

Output
6512
six five one two

A shop stock map holds four counts. The total is 43.

Sort a list of the values and pick the last two.

Those two add to 27.

Python
stock = {'pens': 12, 'clips': 7, 'rulers': 15, 'erasers': 9}
ordered = sorted(stock.values())
print(ordered[-1])
print(ordered[-2])

Output
15
12

Keys are friend labels.

Values are extension numbers stored as text, not as money.

You can list, add, delete, change, test, and show keys in sorted order.

Python
friends = {'Friend A': '2101', 'Friend B': '2104', 'Friend C': '2110'}
for name in friends:
    print(name, friends[name])
friends['Friend D'] = '2118'
print(friends)
del friends['Friend B']
print(friends)
friends['Friend A'] = '2199'
print(friends)
print('Friend C' in friends)
print(sorted(friends))

Output
Friend A 2101
Friend B 2104
Friend C 2110
{'Friend A': '2101', 'Friend B': '2104', 'Friend C': '2110', 'Friend D': '2118'}
{'Friend A': '2101', 'Friend C': '2110', 'Friend D': '2118'}
{'Friend A': '2199', 'Friend C': '2110', 'Friend D': '2118'}
True
['Friend A', 'Friend C', 'Friend D']

Start a new key at 1 the first time you see it.

Count letters in "books". How many times does o appear? Walk each letter.

Goal. Build a frequency map and read o.

Start. freq is {}.

b. New key. freq[b] = 1.

o. New key. freq[o] = 1.

o. Already a key. freq[o] becomes 2.

k. New key. freq[k] = 1.

s. New key. freq[s] = 1.

Check. Counts 1 + 2 + 1 + 2 = 6 letters.

Result: o appears 2 times. The map holds o: 2.

Check these without looking back. Then read the notes.

Watch out: Start a new key at 1 the first time you see it. Adding 1 to a missing key is a KeyError. Check membership first, or use get.

⚡ Quick Check Flashcards4 questions
Question 1
In the odd map, is 2 a key?
Try answering before revealing!
Question 2
Why store a number as text in convert(num)?
Try answering before revealing!
Question 3
What is the first step when a letter is new in a frequency map?
Try answering before revealing!
Question 4
How do you print keys of friends in alphabetical order?
Try answering before revealing!

Summary

175 words · 1 min read
  • A tuple is an ordered, immutable sequence written in parentheses.
  • A one-value tuple needs a trailing comma. A comma row without parentheses is still a tuple.
  • You read tuples with indexes and slices. Item assignment raises TypeError.
  • A list inside a tuple can still be edited, because the list is mutable.
  • + joins tuples, * repeats them, in tests values, and a slice builds a new tuple.
  • count and index are tuple methods. len, min, max, sum, sorted and tuple() are built-ins.
  • Tuple assignment unpacks values into names and swaps two variables with a, b = b, a.
  • Nested tuples store records. Two indexes pick a record and then a field.
  • A dictionary maps unique immutable keys to values, written as key: value in curly braces.
  • Dictionaries are mutable: add or overwrite with d[k] = v. in tests keys.
  • Traverse with keys, values() or items(). get, update, del and clear are the common tools.
  • Use dictionaries for labelled tables, letter frequencies and digit-to-word maps.
Explain each important word in your own words. Then say why the rule works.

Exercises

588 words · 3 min read

These questions are new. Show your thinking. For programs, write your answer before you run the code.

10.1 Predict print((23, 1, 45, 67, 45, 9, 55, 45).index(45)).

10.2 Predict print((23, 1, 45, 67, 45, 9, 55, 45).count(45)).

10.3 Predict the output of this program.

Python
t1 = (23, 1, 45)
t2 = (100, 200)
print(t1 + t2)

10.4 Predict print(len((100, 200))), print(max((23, 1, 45, 67))), print(min((23, 1, 45, 67))), and print(sum((100, 200))).

10.5 Predict print(sorted((23, 1, 45, 9))) and then print the original tuple if it was named t = (23, 1, 45, 9) after sorted(t).

10.6 Why does len((5)) fail, and how do you correct it?

10.7 Predict print((10, 20, 30, 40, 50, 60, 70, 80)[::-1]).

10.8 Predict print("green" in ("red", "green", "blue")) and print(("go",) * 3).

10.9 A tuple holds a list: mix = (1, [8, 9]). Can you set mix[1][0] = 3? Can you set mix[0] = 2?

10.10 Predict a and b after this swap.

Python
a = 17
b = 4
a, b = b, a
print(a, b)

10.11 A function returned this pair. Predict the two printed lines.

Python
area, edge = (20, 18)
print(area)
print(edge)

10.12 Predict what this nested-tuple program prints.

Python
group = ((201, 'Student A', 88), (202, 'Student B', 91))
print(group[1][2])

10.13 Why choose a tuple instead of a list for a record of seat, label and mark?

10.14 When is a dictionary a better store than a tuple?

10.15 Predict the three printed lines from this dictionary program.

Python
cap = {'North': 'City A', 'East': 'City B', 'West': 'City C'}
print(cap.get('East'))
print(list(cap.keys()))
print('East' in cap)

10.16 Predict the two printed lines from this dictionary program.

Python
cap = {'North': 'City A', 'East': 'City B', 'West': 'City C'}
print(cap.get('South'))
print(len(cap))

10.17 Predict the dictionary this program prints.

Python
bag = {'pens': 12, 'clips': 7}
bag.update({'glue': 4})
del bag['clips']
print(bag)

10.18 Predict the letter counts this program prints, in first-seen order.

Python
text = 'books'
freq = {}
for ch in text:
    if ch in freq:
        freq[ch] += 1
    else:
        freq[ch] = 1
for key in freq:
    print(key, ':', freq[key])

10.19 Predict the words this digit converter prints.

Python
def convert(num):
    names = {0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine'}
    result = ''
    for ch in num:
        result = result + ' ' + names[int(ch)]
    return result.strip()
print(convert('6512'))

10.20 Predict the two highest stock counts, largest first.

Python
stock = {'pens': 12, 'clips': 7, 'rulers': 15, 'erasers': 9}
ordered = sorted(stock.values())
print(ordered[-1], ordered[-2])

Answers

  1. 10.1: 2
  2. 10.2: 3
  3. 10.3: (23, 1, 45, 100, 200)
  4. 10.4: len 2; max 67; min 1; sum 300.
  5. 10.5: sorted prints [1, 9, 23, 45]. The original tuple is still (23, 1, 45, 9).
  6. 10.6: (5) is the integer 5, so len raises TypeError. Write (5,) with a comma, then len is 1.
  7. 10.7: (80, 70, 60, 50, 40, 30, 20, 10)
  8. 10.8: membership True; repeat ('go', 'go', 'go').
  9. 10.9: Yes to the first, because the inner list is mutable. No to the second: replacing a tuple slot is TypeError.
  10. 10.10: 4 17
  11. 10.11: prints 20, then 18
  12. 10.12: 91
  13. 10.13: The record should stay in a fixed order and should not be edited by accident. A tuple is immutable and still ordered.
  14. 10.14: When you look up by a label rather than by a place, such as hours for Worker B, or the count of the letter o.
  15. 10.15: prints City B, then ['North', 'East', 'West'], then True
  16. 10.16: prints None, then 3
  17. 10.17: {'pens': 12, 'glue': 4}
  18. 10.18: prints b : 1, then o : 2, then k : 1, then s : 1
  19. 10.19: six five one two
  20. 10.20: 15 12
Up next
Continue to the next chapter