Programming in Python / Lists and dictionaries
Lists and dictionaries
All 5 lessons, in order.
The unit at a glance
- Build an ordered list
A queue at a counter has a first person, a second and so on, and each person keeps a place in line.
- Update an item by index
A whiteboard of scores can be wiped and rewritten, one cell at a time, and a new row can be added at the bottom.
- Look up a key
A phone book is not read by position: you look up a name and read the number beside it.
- Count repeated labels
A tally sheet for a vote has one line for each answer.
- Choose a list or dictionary for a roster
A class has a seating order and a room for each student.
Rules (5)
- Build an ordered list
A list is written as values between square brackets, separated by commas, and keeps them in order.
a[i]gives the item at indexi, counted from 0;a[-1]gives the last item;len(a)gives the number of items. An index fromlen(a)up raises an IndexError. - Update an item by index
A list is mutable.
a[i] = vreplaces the item at indexiwithvand keeps the length;a.append(v)addsvat the end and makes the list one item longer. A string is immutable: assigning to one of its characters raises a TypeError. - Look up a key
A dictionary holds key: value pairs with unique keys.
d[k]gives the value stored with keyk, and a missing key raises a KeyError.d[k] = vadds the pair, or replaces the value whenkis already a key.k in disTruewhenkis a key. - Count repeated labels
To count labels, start with an empty dictionary. For each label, add 1 to its value when it is already a key, and store it with 1 when it is not. After the loop, each key's value is the number of times that label appeared.
- Choose a list or dictionary for a roster
Use a list when the order or position of values matters, and read it by index. Use a dictionary when values are looked up by a key such as a name, and read it by key. Keys of a dictionary are unique; values and list items may repeat.
Recipes (5)
- Build an ordered list
- Write the items in order between square brackets, separated by commas.
- Number the items from 0 under the list as you trace it.
- Before reading an item, check its index against the length: in a list that is not empty, the largest index is one less than
len(), and an empty list has no item to read. - To read an item, use its number in square brackets after the list's name. Use -1 for the last item.
- To work through every item, write a for loop over the list.
- Update an item by index
- Write the list with each index under its item.
- Before
name[i] = value, check that indexinames an item: for a list of n items, from 0 up to n - 1, or from -1 back to -n counting from the end. - For
name[i] = value, cross out the item at indexiand write the new value there. - For
name.append(value), write the value after the last item and add 1 to the length. - Print the list to see its items after the changes, and print
len()of it to see how many items it holds.
- Look up a key
- Write each key with its value, in pairs, as the dictionary is built.
- For
d[k] = v, replace the value ifkis already a key; otherwise add the new pair at the end, since the keys keep the order they were added in. - For
d[k], find the key and read its value; if the key is missing, the program stops with a KeyError. - For
k in d, answerTruewhenkis one of the keys, andFalseotherwise.
- Count repeated labels
- Set
counts = {}above the loop. - Loop over the labels with a for loop.
- Inside the loop, test
if label in counts:. - When it is true, write
counts[label] += 1; otherwise writecounts[label] = 1, which stores the new key. - After the loop, read a count with
counts[label]or print the whole dictionary.
- Set
- Choose a list or dictionary for a roster
- Write the questions the program must answer.
- If a question asks by position, such as first or next, keep a list.
- If a question asks by a name or code, keep a dictionary with that name as the key.
- Check the keys: each key holds one value only.
- Use both when the program needs both kinds of question.
Traps (5)
- Build an ordered list
The usual slip is counting from 1. In a list of 3 items,
queue[3]is not the last item: it is past the end, and the program stops with an IndexError. Usequeue[2], orqueue[-1].Square brackets do two jobs here. In
["Ada", "Ben"]they make a list; after a name, as inqueue[0], they read an item. - Update an item by index
Assigning the result of
appendto the list's name loses that name for the list.appendchanges the list and gives backNone, so afterscores = scores.append(10)the list has grown, butscoresnamesNone.To add an item, use
append, not an index one past the end:scores[3] = 10on a list of three items stops with an IndexError. - Look up a key
Reading a key that was never stored stops the program with a KeyError. When a key may be missing, test it with
infirst.A dictionary is not read by position.
phone[0]looks for the key 0, not the first pair, and here it stops with a KeyError because 0 is not one of its keys. - Count repeated labels
Writing only
counts[vote] += 1stops at the first vote with a KeyError, because the count is read before anything was stored for that key. Theelsebranch stores the first 1.Setting
counts = {}inside the loop empties the tally on every pass, and only the last vote would be left. Put it above the loop. - Choose a list or dictionary for a roster
Using a name as a list index stops the program:
seats["Cy"]raises a TypeError, because a list index is a whole number. Keep a dictionary for lookups by name.Using one dictionary for values that share a key loses one of them: storing a second value with the same key replaces the first.
Lesson 1 of 5
Build an ordered list
Open this lessonLeans on 1Comes back in 0
Leans on
Comes back in
No lesson links recorded.
1 In plain words
A queue at a counter has a first person, a second and so on, and each person keeps a place in line.
A list keeps values in order in the same way. Write it as values separated by commas between square brackets, such as ["Ada", "Ben", "Cy"]. Each value is an item of the list.
Items are found by their index, a position counted from 0. In queue = ["Ada", "Ben", "Cy"], queue[0] is "Ada" and queue[2] is "Cy". An index of -1 counts from the end and gives the last item. len(queue) gives the number of items, 3.
Remember one sentence: a list keeps its items in order, numbered from 0. To look it up, see section 3.1.3 of the Python 3.13 tutorial, on lists.
2 Picture it
A table of the list queue. Index 0 holds Ada, the first item. Index 1 holds Ben. Index 2 holds Cy, which index -1 also gives. The row for index 0 is marked.
3 Why
Counting from 0 means the first item is 0 steps from the start. The last item of a list of 3 is then at index 2, one less than the length.
An index of 3 in a list of 3 items points past the end. Python stops the program with an IndexError, the error for a sequence index out of range.
A list is a sequence, like a string, so a for loop works through its items in order. Printing a whole list shows its items in square brackets, with quotation marks around text items.
4 The rule
A list is written as values between square brackets, separated by commas, and keeps them in order.
a[i] gives the item at index i, counted from 0; a[-1] gives the last item; len(a) gives the number of items. An index from len(a) up raises an IndexError.
5 How
- Write the items in order between square brackets, separated by commas.
- Number the items from 0 under the list as you trace it.
- Before reading an item, check its index against the length: in a list that is not empty, the largest index is one less than
len(), and an empty list has no item to read. - To read an item, use its number in square brackets after the list's name. Use -1 for the last item.
- To work through every item, write a for loop over the list.
6 Worked example
Read a list by index and by loop
queue = ["Ada", "Ben", "Cy"]
print(queue[0])
print(queue[-1])
print(len(queue))
for name in queue:
print(f"Next: {name}")
Standard input
Empty
Standard output
Ada
Cy
3
Next: Ada
Next: Ben
Next: Cy
Predict the six output lines first. Then save the code as queue.py and run the file. queue[0] is the first item, queue[-1] the last, and the loop visits the items in order.
Ask for an index past the end
queue = ["Ada", "Ben", "Cy"]
print(queue[3])
Standard input
Empty
Standard output
Empty
Exception IndexError
Save the two lines as end.py and run the file. The list has items at 0, 1 and 2, so index 3 is out of range and the program stops with an IndexError.
Trace
| Line | Value | Output | Explanation |
|---|---|---|---|
print(queue[0]) | "Ada" | Ada | Index 0 is the first item. |
print(queue[-1]) | "Cy" | Cy | Index -1 is the last item. |
print(len(queue)) | 3 | 3 | The list has three items. |
| the for loop | each name in turn | Next: Ada, Next: Ben, Next: Cy | The loop name takes each item in order. |
7 The trap
The usual slip is counting from 1. In a list of 3 items, queue[3] is not the last item: it is past the end, and the program stops with an IndexError. Use queue[2], or queue[-1].
Square brackets do two jobs here. In ["Ada", "Ben"] they make a list; after a name, as in queue[0], they read an item.
Quick checks
Quick check 1 of 2
Predict what this program displays. The program reads no input.
colors = ["red", "green", "blue", "gold"]
print(colors[1])
print(colors[-1])
print(len(colors))Show the steps and the answer
It displays green, gold and 4, each on its own line.
Why: Index 1 is the second item, green. Index -1 is the last item, gold. The list has four items.
Source: Python Software Foundation, Python 3.13 Tutorial, 3.1.3 Lists
Quick check 2 of 2
A list days holds 7 items. What is the largest index you can use with it, counting from the start?
Show the steps and the answer
The largest index is 6.
Why: Counting from 0, the indexes from the start run from 0 to one less than the length, so 0 to 6.
Source: Python Software Foundation, Python 3.13 Tutorial, 3.1.3 Lists
Sources
- Python 3.13 Tutorial, 3.1.3 Lists. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
- Python 3.13 Library Reference, Built-in Exceptions: IndexError. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
- Python 3.13 Tutorial, 4.2 for Statements. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
Lesson 2 of 5
Update an item by index
Open this lessonLeans on 0Comes back in 0
Leans on
No lesson links recorded.
Comes back in
No lesson links recorded.
1 In plain words
A whiteboard of scores can be wiped and rewritten, one cell at a time, and a new row can be added at the bottom.
A list can be changed in the same way: it is mutable. Assigning to an index, as in scores[1] = 6, replaces the item at that index. The method append, as in scores.append(10), adds an item at the end, and the list grows by one.
A string is not mutable. Assigning to one character of a string stops the program with a TypeError.
Remember one sentence: an index assignment replaces one item, and append adds one at the end. To look it up, see sections 3.1.3 and 5.1 of the Python 3.13 tutorial, on lists.
2 Picture it
A table of the list scores after each line. At the start it holds 7, 4 and 9, three items. After scores[1] = 6 it holds 7, 6 and 9, still three. After scores.append(10) it holds 7, 6, 9 and 10, four items. The row for scores[1] = 6 is marked.
3 Why
In scores[1] = 6 the left side names one place in the list. Python puts the new value there and the old value, 4, is gone. The other items and the length do not change.
append changes the list itself and adds the item after the last one. It gives back None, so a line such as scores = scores.append(10) would leave scores naming None. Call it on a line of its own.
Index assignment replaces an item that exists; it does not add one. scores[4] = 10 on a list of 4 items stops with an IndexError.
4 The rule
A list is mutable.
a[i] = v replaces the item at index i with v and keeps the length; a.append(v) adds v at the end and makes the list one item longer. A string is immutable: assigning to one of its characters raises a TypeError.
5 How
- Write the list with each index under its item.
- Before
name[i] = value, check that indexinames an item: for a list of n items, from 0 up to n - 1, or from -1 back to -n counting from the end. - For
name[i] = value, cross out the item at indexiand write the new value there. - For
name.append(value), write the value after the last item and add 1 to the length. - Print the list to see its items after the changes, and print
len()of it to see how many items it holds.
6 Worked example
Replace an item and add one
scores = [7, 4, 9]
scores[1] = 6
scores.append(10)
print(scores)
print(len(scores))
Standard input
Empty
Standard output
[7, 6, 9, 10]
4
Predict the two output lines first, then run the file. The second score changes from 4 to 6, and 10 joins the end.
Try to change one character of a string
code = "cat"
code[0] = "b"
Standard input
Empty
Standard output
Empty
Exception TypeError
Save the two lines as code.py and run the file. A string cannot be changed, so the second line stops the program with a TypeError. Build a new string instead.
Trace
| Line | scores | Output | Explanation |
|---|---|---|---|
scores = [7, 4, 9] | [7, 4, 9] | — | A list of three items. |
scores[1] = 6 | [7, 6, 9] | — | Index 1, the second item, is replaced. |
scores.append(10) | [7, 6, 9, 10] | — | 10 is added at the end. |
print(scores) | [7, 6, 9, 10] | [7, 6, 9, 10] | The list is printed in square brackets. |
print(len(scores)) | [7, 6, 9, 10] | 4 | The list now has four items. |
7 The trap
Assigning the result of append to the list's name loses that name for the list. append changes the list and gives back None, so after scores = scores.append(10) the list has grown, but scores names None.
To add an item, use append, not an index one past the end: scores[3] = 10 on a list of three items stops with an IndexError.
Quick checks
Quick check 1 of 2
Predict what this program displays. The program reads no input.
marks = [3, 5, 8]
marks[0] = 4
marks.append(2)
print(marks)Show the steps and the answer
It displays [4, 5, 8, 2].
Why: Index 0 changes from 3 to 4, and append adds 2 at the end.
Source: Python Software Foundation, Python 3.13 Tutorial, 3.1.3 Lists
Quick check 2 of 2
A list row holds 5 items. After row[2] = 0, how many items does it hold? After row.append(0) as well?
Show the steps and the answer
It holds 5 items after the assignment, and 6 after the append.
Why: Index assignment replaces an item and keeps the length. append adds one item at the end.
Source: Python Software Foundation, Python 3.13 Tutorial, 3.1.3 Lists
Sources
- Python 3.13 Tutorial, 3.1.3 Lists. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
- Python 3.13 Tutorial, 5.1 More on Lists. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
- Python 3.13 Tutorial, 3.1.2 Text. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
- Python 3.13 Library Reference, Built-in Exceptions: IndexError. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
Lesson 3 of 5
Look up a key
Open this lessonLeans on 0Comes back in 0
Leans on
No lesson links recorded.
Comes back in
No lesson links recorded.
1 In plain words
A phone book is not read by position: you look up a name and read the number beside it.
A dictionary works that way. It holds key: value pairs between curly braces, such as {"Ada": 4098, "Ben": 4139}. Each key appears once, and phone["Ada"] gives the value stored with the key "Ada".
Storing with a key, as in phone["Cy"] = 4127, adds the pair when the key is new and replaces the old value when the key is already there. "Ben" in phone is True when "Ben" is a key.
Remember one sentence: a dictionary finds a value by its key. To look it up, see section 5.5 of the Python 3.13 tutorial, on dictionaries.
2 Picture it
A table of the dictionary phone after the worked example runs. The key Ada holds 4100, the key Ben 4139 and the key Cy 4127. The row for Ada is marked, since its value was replaced.
3 Why
A list is indexed by whole-number positions; a dictionary is indexed by its keys. Strings and numbers can be keys.
Keys are unique within one dictionary, so storing with a key in use forgets the old value. In the worked example, phone["Ada"] = 4100 replaces 4098, and the dictionary still holds three pairs.
Reading a key that is not there stops the program with a KeyError. Test with in first. Printing a dictionary shows its pairs in curly braces, in the order the keys were added.
4 The rule
A dictionary holds key: value pairs with unique keys.
d[k] gives the value stored with key k, and a missing key raises a KeyError. d[k] = v adds the pair, or replaces the value when k is already a key. k in d is True when k is a key.
5 How
- Write each key with its value, in pairs, as the dictionary is built.
- For
d[k] = v, replace the value ifkis already a key; otherwise add the new pair at the end, since the keys keep the order they were added in. - For
d[k], find the key and read its value; if the key is missing, the program stops with a KeyError. - For
k in d, answerTruewhenkis one of the keys, andFalseotherwise.
6 Worked example
Store, replace and read by key
phone = {"Ada": 4098, "Ben": 4139}
phone["Cy"] = 4127
phone["Ada"] = 4100
print(phone["Ada"])
print(phone)
print("Ben" in phone)
Standard input
Empty
Standard output
4100
{'Ada': 4100, 'Ben': 4139, 'Cy': 4127}
True
Predict the three output lines first, then run the file. Cy is a new key, so its pair is added; Ada is already a key, so its value is replaced. Python prints the text keys with single quotation marks.
Read a key that is not there
phone = {"Ada": 4098}
print(phone["Dee"])
Standard input
Empty
Standard output
Empty
Exception KeyError
Save the two lines as dee.py and run the file. Dee is not a key, so the program stops with a KeyError.
Trace
| Line | phone | Output | Explanation |
|---|---|---|---|
phone = {...} | Ada 4098, Ben 4139 | — | Two pairs. |
phone["Cy"] = 4127 | Ada 4098, Ben 4139, Cy 4127 | — | Cy is new, so the pair is added. |
phone["Ada"] = 4100 | Ada 4100, Ben 4139, Cy 4127 | — | Ada is already a key, so 4098 is replaced. |
print(phone["Ada"]) | unchanged | 4100 | The value stored with Ada. |
print(phone) | unchanged | {'Ada': 4100, 'Ben': 4139, 'Cy': 4127} | The pairs are printed in curly braces, in the order the keys were added. |
print("Ben" in phone) | unchanged | True | Ben is a key. |
7 The trap
Reading a key that was never stored stops the program with a KeyError. When a key may be missing, test it with in first.
A dictionary is not read by position. phone[0] looks for the key 0, not the first pair, and here it stops with a KeyError because 0 is not one of its keys.
Quick checks
Quick check 1 of 2
Predict what this program displays. The program reads no input.
stock = {"pens": 4, "cups": 2}
stock["pens"] = 9
stock["jars"] = 1
print(stock["pens"])
print(stock)Show the steps and the answer
It displays 9 and then {'pens': 9, 'cups': 2, 'jars': 1}.
Why: pens is already a key, so its value becomes 9 and it keeps its place. jars is new, so a third pair is added at the end.
Source: Python Software Foundation, Python 3.13 Tutorial, 5.5 Dictionaries
Quick check 2 of 2
ages = {"Ada": 12}. What does print("Ben" in ages) display, and what does print(ages["Ben"]) do?
Show the steps and the answer
The first displays False. The second stops the program with a KeyError.
Why: Ben is not a key. in answers the question; reading the missing key raises KeyError.
Source: Python Software Foundation, Python 3.13 Tutorial, 5.5 Dictionaries
Sources
- Python 3.13 Tutorial, 5.5 Dictionaries. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
- Python 3.13 Library Reference, Built-in Exceptions: KeyError. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
Lesson 4 of 5
Count repeated labels
Open this lessonLeans on 0Comes back in 0
Leans on
No lesson links recorded.
Comes back in
No lesson links recorded.
1 In plain words
A tally sheet for a vote has one line for each answer. Each new ballot either adds a mark to a line already there or starts a new line.
A dictionary makes the same tally: each label is a key, and its value is how many times it has appeared. Go through the labels with a for loop. If a label is already a key, add 1 to its count; otherwise store it with the count 1.
Remember one sentence: add 1 for a label you have seen, store 1 for a new one. To look up the dictionary operations, see section 5.5 of the Python 3.13 tutorial.
2 Picture it
A table of the first three passes of the vote count. The first vote, tea, is not a key, so tea is stored with 1. Milk is not a key either, so milk is stored with 1. The next tea is already a key, so its count becomes 2. The third row is marked.
3 Why
The if decides between two different steps. counts[vote] += 1 reads the old count, so it works only for a label already stored; for a new label that read would raise a KeyError. So a new label is stored with 1 instead.
The counts start as an empty dictionary, {}, before the loop, like any running total.
When the labels are in a list and only one label's count is needed, votes.count("tea") gives it directly. The dictionary tally gives every label's count in one pass of the loop.
- Python Software Foundation, Python 3.13 Language Reference, 8.1 The if statement
- Python Software Foundation, Python 3.13 Library Reference, Built-in Exceptions: KeyError
- Python Software Foundation, Python 3.13 Language Reference, 7.2.1 Augmented assignment statements
- Python Software Foundation, Python 3.13 Tutorial, 5.5 Dictionaries
- Python Software Foundation, Python 3.13 Tutorial, 5.1 More on Lists
- Python Software Foundation, Python 3.13 Tutorial, 4.2 for Statements
4 The rule
To count labels, start with an empty dictionary.
For each label, add 1 to its value when it is already a key, and store it with 1 when it is not. After the loop, each key's value is the number of times that label appeared.
5 How
- Set
counts = {}above the loop. - Loop over the labels with a for loop.
- Inside the loop, test
if label in counts:. - When it is true, write
counts[label] += 1; otherwise writecounts[label] = 1, which stores the new key. - After the loop, read a count with
counts[label]or print the whole dictionary.
- Python Software Foundation, Python 3.13 Tutorial, 5.5 Dictionaries
- Python Software Foundation, Python 3.13 Tutorial, 4.2 for Statements
- Python Software Foundation, Python 3.13 Language Reference, 8.1 The if statement
- Python Software Foundation, Python 3.13 Language Reference, 7.2.1 Augmented assignment statements
6 Worked example
Count five votes
votes = ["tea", "milk", "tea", "water", "tea"]
counts = {}
for vote in votes:
if vote in counts:
counts[vote] += 1
else:
counts[vote] = 1
print(counts)
print(counts["tea"])
Standard input
Empty
Standard output
{'tea': 3, 'milk': 1, 'water': 1}
3
Predict the two output lines first, then run the file. tea is counted three times; milk and water once each, and the keys appear in the order they were first stored.
Trace
| vote | In counts? | counts after the pass | Explanation |
|---|---|---|---|
| tea | no | tea 1 | A new label is stored with 1. |
| milk | no | tea 1, milk 1 | Another new label. |
| tea | yes | tea 2, milk 1 | tea is a key, so 1 is added. |
| water | no | tea 2, milk 1, water 1 | A third label is stored with 1. |
| tea | yes | tea 3, milk 1, water 1 | tea reaches 3. |
7 The trap
Writing only counts[vote] += 1 stops at the first vote with a KeyError, because the count is read before anything was stored for that key. The else branch stores the first 1.
Setting counts = {} inside the loop empties the tally on every pass, and only the last vote would be left. Put it above the loop.
- Python Software Foundation, Python 3.13 Library Reference, Built-in Exceptions: KeyError
- Python Software Foundation, Python 3.13 Language Reference, 7.2.1 Augmented assignment statements
- Python Software Foundation, Python 3.13 Language Reference, 8.1 The if statement
- Python Software Foundation, Python 3.13 Tutorial, 5.5 Dictionaries
- Python Software Foundation, Python 3.13 Tutorial, 4.2 for Statements
Quick checks
Quick check 1 of 2
Predict what this program displays. The program reads no input.
counts = {}
for ch in "abba":
if ch in counts:
counts[ch] += 1
else:
counts[ch] = 1
print(counts)Show the steps and the answer
It displays {'a': 2, 'b': 2}.
Why: a is stored with 1, b is stored with 1, then b and a each get 1 more. The keys keep the order a, b.
Source: Python Software Foundation, Python 3.13 Tutorial, 5.5 Dictionaries
Quick check 2 of 2
tags = ["red", "blue", "red", "red"]. What does print(tags.count("red")) display?
Show the steps and the answer
It displays 3.
Why: The list method count gives the number of times the value appears in the list.
Source: Python Software Foundation, Python 3.13 Tutorial, 5.1 More on Lists
Sources
- Python 3.13 Tutorial, 5.5 Dictionaries. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
- Python 3.13 Language Reference, 8.1 The if statement. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
- Python 3.13 Library Reference, Built-in Exceptions: KeyError. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
- Python 3.13 Language Reference, 7.2.1 Augmented assignment statements. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
- Python 3.13 Tutorial, 5.1 More on Lists. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
- Python 3.13 Tutorial, 4.2 for Statements. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
Lesson 5 of 5
Choose a list or dictionary for a roster
Open this lessonLeans on 0Comes back in 0
Leans on
No lesson links recorded.
Comes back in
No lesson links recorded.
1 In plain words
A class has a seating order and a room for each student. The seating order is about position: who sits first, second, third. The rooms are about lookup: which room is Cy's?
A list fits the first job: its items keep their order and are read by position. A dictionary fits the second: it reads a value by a key, such as a name, without counting along.
Remember one sentence: position means a list, lookup by name means a dictionary. The choice is this lesson's advice; the two types are described in sections 3.1.3 and 5.5 of the Python 3.13 tutorial.
2 Picture it
A table of three roster questions. Who sits second is answered by the list, read with seats[1]. Cy's room is answered by the dictionary, read with rooms with the key Cy. Who is first is answered by the list, read with seats[0]. The first two rows are marked.
3 Why
A list of names can say where Cy sits, but it holds no rooms. The plain way to find a room by name is to store the rooms by name: a dictionary keyed by name reads Cy's room directly.
Each name used as a key holds one room, because keys are unique. Several names can hold the same room, because values can repeat.
A list allows repeats and keeps order, so it suits a sequence such as a seating plan or a queue.
4 The rule
Use a list when the order or position of values matters, and read it by index.
Use a dictionary when values are looked up by a key such as a name, and read it by key. Keys of a dictionary are unique; values and list items may repeat.
5 How
- Write the questions the program must answer.
- If a question asks by position, such as first or next, keep a list.
- If a question asks by a name or code, keep a dictionary with that name as the key.
- Check the keys: each key holds one value only.
- Use both when the program needs both kinds of question.
6 Worked example
Keep a seating list and a room dictionary
seats = ["Ada", "Ben", "Cy"]
rooms = {"Ada": "B2", "Ben": "A1", "Cy": "B2"}
print(seats[1])
print(rooms["Cy"])
seats.append("Dee")
rooms["Dee"] = "A1"
print(seats)
print(rooms["Dee"])
Standard input
Empty
Standard output
Ben
B2
['Ada', 'Ben', 'Cy', 'Dee']
A1
Predict the four output lines first, then run the file. The list answers who sits second; the dictionary answers Cy's room without counting along. Dee is added to both.
Trace
| Line | Reads | Output | Explanation |
|---|---|---|---|
print(seats[1]) | the item at index 1 | Ben | Position 1 is the second seat. |
print(rooms["Cy"]) | the value of key Cy | B2 | The room is read by name. |
seats.append("Dee"), rooms["Dee"] = "A1" | — | — | Dee joins the end of the list and becomes a key. |
print(seats) | the whole list | ['Ada', 'Ben', 'Cy', 'Dee'] | The list keeps its order. |
print(rooms["Dee"]) | the value of key Dee | A1 | The new pair is read by name. |
7 The trap
Using a name as a list index stops the program: seats["Cy"] raises a TypeError, because a list index is a whole number. Keep a dictionary for lookups by name.
Using one dictionary for values that share a key loses one of them: storing a second value with the same key replaces the first.
Quick checks
Quick check 1 of 2
A program must answer two questions about a library: which book is fifth on the returns trolley, and which shelf holds a given title. Which type fits each question?
Show the steps and the answer
A list for the trolley, and a dictionary from title to shelf.
Why: The fifth book is a question of position, read with an index. The shelf is looked up by the title, a key.
Source: Python Software Foundation, Python 3.13 Tutorial, 5.5 Dictionaries
Sources
- Python 3.13 Tutorial, 3.1.3 Lists. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
- Python 3.13 Tutorial, 5.5 Dictionaries. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
- Python 3.13 Library Reference, Built-in Types: Common Sequence Operations. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
- Python 3.13 Tutorial, 5.1 More on Lists. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.
- Python 3.13 Library Reference, Built-in Exceptions: IndexError. Python Software Foundation. Python Software Foundation License Version 2. Read 2 Dec 2026.