Skip to content
Exit presentation

Data Handling II: Databases & Structured Data

Naming the columns

A name is not a place in the rows. A position is. The headers list holds the four column names in order. The code headers.indexOf(name) gives the position of that name in the list.

The headers list, four names in order.
Step 1 of 4
  1. The headers list, four names in order.
  2. Positions are written below: 0 to 3.
  3. indexOf('due') points at position 3.
  4. indexOf('marks') finds nothing: answer −1.

The rule

The headers list turns a column's name into a position. Find the position first, then fetch the field. Minus one is an answer. Do not use it as a position. It means no such column exists.

A function is named code that gives back one value. Here wanted is the column name to find.

  1. function fieldIndex(headers, wanted) {
  2. return headers.indexOf(wanted);
  3. }

indexOf gives −1 when the name is not in the list. Columns sit at positions 0 and up. So −1 is no column's position.

fieldIndex(headers, 'name') gives 1. fieldIndex(headers, 'marks') gives −1, because the register has no marks column.

Suppose the school changes the order of the columns. headers.indexOf still finds the right one. A hand-typed position such as 3 would name the wrong column.

Watch out!

In real Python, a fetch at −1 does not stop. It quietly gives the last field. So check for −1 before you fetch.

The mistake comes only when you fetch with −1. Then this course's runner stops. It names the position and the row's length.

Below, make fieldIndex give the right position. It must also answer for a missing column, such as marks.

Loading lab…

A position-finder answers every question — with a position, or with −1.

Jump to lesson

This track

  1. 0 Start here
  2. 1 One record, one row
  3. 2 The naming value
  4. 3 Naming the columns
  5. 4 Asking the register one question
  6. 5 Two conditions, both true
  7. 6 The answer, in order
  8. 7 Counting the groups in the answer
  9. 8 What a database adds
  10. 9 The big picture
  11. 10 Track quiz

Other tracks