Lists and dictionaries: crash course
about 4 min to listen5 lessons0 questions to tryUnit 5 of 6
Short view. Each lesson's rule, its steps and its trap. Switch to Full for a worked example and a question to try in every lesson.Full view. Each lesson's rule, its steps, one worked example with Watch it solved, the trap, and one question to try.
Starts here no skill from another unit needed first
1 Build an ordered list
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.
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.
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.
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.
2 Update an item by index
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.
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.
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.
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.
3 Look up a key
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.
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.
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.
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.
4 Count repeated labels
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.
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
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.
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
5 Choose a list or dictionary for a roster
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.
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.
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.
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.