Lists and dictionaries — quick review
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.
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.
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.
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.
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.
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.
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.
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.
Look up a key
A phone book is not read by position: you look up a name and read the number beside it.
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.
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.
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.
Count repeated labels
A tally sheet for a vote has one line for each answer.
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.
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.
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.
Choose a list or dictionary for a roster
A class has a seating order and a room for each student.
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.
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.
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.