Course contents · Chapter 2
Building with AIChapter 2 of 42 min reading + practice

Store related observations clearly

Lists hold ordered collections; dictionaries associate keys with values.

Lists hold ordered collections; dictionaries associate keys with values.

Choose a structure that preserves the meaning of each field. A list of dictionaries can represent fictional records with named attributes.

Preserve relationships inside the data structure

A list preserves a sequence of values. A dictionary associates keys with values. A list of dictionaries can represent workshops while keeping each workshop's name and attendance together. Accessing rows[0]['name'] first selects a record by position, then selects a value by key.

Separate lists for names and attendance create a relationship that exists only through matching positions. Sorting one list independently breaks that relationship without necessarily producing an exception. This is a particularly dangerous error because the program can continue printing plausible but incorrect reports.

Modify the example by adding a workshop with zero attendees. Calculate the expected total before running it. Then misspell one dictionary key and inspect the KeyError. Decide whether a missing attendance field should be rejected or handled through an explicit alternative; quietly treating every missing field as zero can hide data problems.

The bigger picture

A Python program transforms values according to explicit operations. To understand a program, trace the values and their types, not just the printed output. Text that looks like a number remains text until an operation converts it.

  1. Read inputs
  2. Trace operations
  3. Run code
  4. Test another case
A working model for this course. Use it to locate where a decision or failure occurs.

Concepts to keep close

Type
The kind of value, which determines the operations that have meaning for it.
Control flow
The order in which statements execute, including branches and loops.
Return value
A result passed back to calling code; printing a result is a different action.

Reasoning through the problem

Keep related fields in one record.

Use explicit dictionary keys.

Read values from the same record when reporting.

Use the idea carefully

Predict output before running a short example. Change one value or operation and explain the new result. Test an ordinary case, an empty input and a boundary. Read errors from the final exception message back to the relevant line. A passing example is evidence about that input, not proof that every possible input works.

Further reading & course resources

Original documentation and teaching references for further investigation.