Quarry School

Lists and dictionaries — quick review

Build an ordered list

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.

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.

Step

  1. Write the items in order between square brackets, separated by commas.

  2. Number the items from 0 under the list as you trace it.

  3. 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.

  4. To read an item, use its number in square brackets after the list's name. Use -1 for the last item.

  5. To work through every item, write a for loop over the list.

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.

Update an item by index

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.

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.

Step

  1. Write the list with each index under its item.

  2. Before name[i] = value, check that index i names an item: for a list of n items, from 0 up to n - 1, or from -1 back to -n counting from the end.

  3. For name[i] = value, cross out the item at index i and write the new value there.

  4. For name.append(value), write the value after the last item and add 1 to the length.

  5. Print the list to see its items after the changes, and print len() of it to see how many items it holds.

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.

Look up a key

In plain words

A phone book is not read by position: you look up a name and read the number beside it.

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.

Step

  1. Write each key with its value, in pairs, as the dictionary is built.

  2. For d[k] = v, replace the value if k is already a key; otherwise add the new pair at the end, since the keys keep the order they were added in.

  3. For d[k], find the key and read its value; if the key is missing, the program stops with a KeyError.

  4. For k in d, answer True when k is one of the keys, and False otherwise.

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.

Count repeated labels

In plain words

A tally sheet for a vote has one line for each answer.

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.

Step

  1. Set counts = {} above the loop.

  2. Loop over the labels with a for loop.

  3. Inside the loop, test if label in counts:.

  4. When it is true, write counts[label] += 1; otherwise write counts[label] = 1, which stores the new key.

  5. After the loop, read a count with counts[label] or print the whole dictionary.

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.

Choose a list or dictionary for a roster

In plain words

A class has a seating order and a room for each student.

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.

Step

  1. Write the questions the program must answer.

  2. If a question asks by position, such as first or next, keep a list.

  3. If a question asks by a name or code, keep a dictionary with that name as the key.

  4. Check the keys: each key holds one value only.

  5. Use both when the program needs both kinds of question.

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.