10. Tuples and dictionaries in Python
About this chapter
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
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.
| Feature | Tuple | List |
|---|---|---|
| Brackets | ( ) | [ ] |
| Can you change an item? | No | Yes |
| Grow in place? | No. Build a new tuple. | Yes. append and friends. |
| Typical use | A frozen record | A 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.
>>> (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.
print(type((20)))
print((20))
print(type((20,)))
print((20,))
seq = 1, 2, 3
print(type(seq))
print(seq)<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.
n = (20)
try:
print(len(n))
except TypeError as err:
print(type(err).__name__)TypeErrorYou 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 is the right end.
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.
pack = (2, 4, 6, 8, 10, 12)
print(pack[0])
print(pack[3])
print(pack[1 + 4])
print(pack[-1])2
8
12
12An index past the end is not allowed.
Python raises IndexError.
pack = (2, 4, 6, 8, 10, 12)
try:
print(pack[15])
except IndexError as err:
print(type(err).__name__)IndexErrorYou 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.
pack = (1, 2, 3, 4, 5)
try:
pack[4] = 10
except TypeError as err:
print(type(err).__name__)TypeErrorThere 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.
mix = (1, 2, 3, [8, 9])
mix[3][1] = 10
print(mix)(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.
Cover the answers. Try each item on paper first.
10.2 Tuple operations
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.
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)(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.
print(('hello', 'world') * 3)
print(('hello',) * 4)('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.
flags = ('red', 'green', 'blue')
print('green' in flags)
print('green' not in flags)
print('yellow' in flags)True
False
FalseA 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 walks the tuple backwards.
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])(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 values.
A step of 2 on a tuple of length 6 keeps 3 values.
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.
10.3 Tuple methods and built-in functions
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.
| Tool | What 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.
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)))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 .
sorted returns a list, not a tuple.
The original pack is still unsorted.
If the value is not in the tuple, index raises ValueError.
pack = (10, 20, 30, 40, 50)
print(pack.index(30))
try:
print(pack.index(90))
except ValueError as err:
print(type(err).__name__)2
ValueErrorsorted(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. , then , then , then .
Result: len is 5, min is 4, max is 11, sum is 41.
Write a short answer. Then check the notes below.
10.4 Tuple assignment
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.
num1, num2 = (10, 20)
print(num1)
print(num2)
record = ('Student A', 40, 'CS')
name, seat, subject = record
print(name)
print(seat)
print(subject)10
20
Student A
40
CSThe 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.
num3, num4 = (10 + 5, 20 + 5)
print(num3)
print(num4)15
25Four names and three values do not match.
Python raises ValueError.
try:
a, b, c, d = (5, 6, 8)
except ValueError as err:
print(type(err).__name__)ValueErrorA 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.
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, holds the old , which was 4.
Then holds the old , which was 17.
The sum is still 21.
a = 17
b = 4
print(a, b)
a, b = b, a
print(a, b)17 4
4 17Python 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. , same as .
Result: a is 4 and b is 17.
Say the result out loud. Then read the answers.
10.5 Nested tuples
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.
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.
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])No Seat Label Mark
1 201 Student A 88
2 202 Student B 91
3 203 Student C 76
91Student 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.
\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.
10.6 Tuple handling
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.
num1 = 5
num2 = 10
print('before', num1, num2)
num1, num2 = num2, num1
print('after', num1, num2)before 5 10
after 10 5A 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 .
Perimeter is .
def box(w, h):
area = w * h
perimeter = 2 * (w + h)
return (area, perimeter)
area, perimeter = box(5, 4)
print(area)
print(perimeter)20
18Start 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.
numbers = tuple()
for num in (9, 8, 10, 12, 15):
numbers = numbers + (num,)
print(numbers)
print(max(numbers))
print(min(numbers))(9, 8, 10, 12, 15)
15
8A 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.
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)('[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.
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)True
True
False
FalseWhen 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.
10.7 Introduction to dictionaries
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.
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.
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)){}
{}
{'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.
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__)89
85
KeyErrorSquare 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
Cover the answers. Try each item on paper first.
10.8 Dictionaries are mutable
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.
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){'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.
week = {
'Mon': {'am': 'maths', 'pm': 'games'},
'Tue': {'am': 'science', 'pm': 'art'},
}
print(week['Mon']['pm'])
week['Tue']['am'] = 'music'
print(week['Tue'])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.
10.9 Dictionary operations
The operators in and not in test keys, not values.
Membership on a dictionary asks about keys.
k in d is True when 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().
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())True
False
False
TrueStudent 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.
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.
10.10 Traversing a dictionary
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.
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)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 : 85All 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.
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.
10.11 Dictionary methods and built-in functions
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.
| Tool | What 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 d | Remove 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.
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)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.
bag = {'pens': 12}
del bag
try:
print(bag)
except NameError as err:
print(type(err).__name__)NameErrorUse 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.
10.12 Manipulating dictionaries
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.
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){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.
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])label hours
Worker A 12
Worker B 34
Worker C 24
Worker D 30
Worker E 25A 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.
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])b : 1
o : 2
k : 1
s : 1A line joining the counts of the letters b, o, k and s in the word books: 1, 2, 1, 2.
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.
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())6512
six five one twoA 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.
stock = {'pens': 12, 'clips': 7, 'rulers': 15, 'erasers': 9}
ordered = sorted(stock.values())
print(ordered[-1])
print(ordered[-2])15
12Keys 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.
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))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.
Summary
- 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.
Exercises
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.
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.
a = 17
b = 4
a, b = b, a
print(a, b)10.11 A function returned this pair. Predict the two printed lines.
area, edge = (20, 18)
print(area)
print(edge)10.12 Predict what this nested-tuple program prints.
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.
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.
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.
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.
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.
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.
stock = {'pens': 12, 'clips': 7, 'rulers': 15, 'erasers': 9}
ordered = sorted(stock.values())
print(ordered[-1], ordered[-2])Answers
- 10.1: 2
- 10.2: 3
- 10.3: (23, 1, 45, 100, 200)
- 10.4: len 2; max 67; min 1; sum 300.
- 10.5: sorted prints [1, 9, 23, 45]. The original tuple is still (23, 1, 45, 9).
- 10.6: (5) is the integer 5, so len raises TypeError. Write (5,) with a comma, then len is 1.
- 10.7: (80, 70, 60, 50, 40, 30, 20, 10)
- 10.8: membership True; repeat ('go', 'go', 'go').
- 10.9: Yes to the first, because the inner list is mutable. No to the second: replacing a tuple slot is TypeError.
- 10.10: 4 17
- 10.11: prints 20, then 18
- 10.12: 91
- 10.13: The record should stay in a fixed order and should not be edited by accident. A tuple is immutable and still ordered.
- 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.
- 10.15: prints City B, then ['North', 'East', 'West'], then True
- 10.16: prints None, then 3
- 10.17: {'pens': 12, 'glue': 4}
- 10.18: prints b : 1, then o : 2, then k : 1, then s : 1
- 10.19: six five one two
- 10.20: 15 12