Specialty Digest

Global English editionLearners’ Study Dashboard — in development
The Knowledge Library for All

Flashcards: open the module flashcards (end-of-module review with workplace questions).

Online Courses / University Track / Python from Zero

Module 4 · Lesson 4 · Core

Choosing a structure, counting and records

Decide between a list and a dictionary, count with a dictionary and combine both into records.

  • 50 minutes
  • Serves O4
  • Assumes M4.L3

Phase 1: Prepare

Step 1 Warm-up recall

From M4.L3: what error does a missing key give?

Private: nothing you type here is sent or stored.

Step 2 Learning goal

By the end of this lesson you can:

  • choose a list or a dictionary for a task (Foundation);
  • count items with a dictionary (Core);
  • read a list of dictionaries (Core).

Phase 2: Teach

Step 3 A familiar example

A survey has many answers, and you want to know how many said each thing. A tally sheet keeps one count per answer. A dictionary is the tally sheet.

Step 4 Clear explanation

Use a list when order or position matters. Use a dictionary when you look things up by name.

List: by position0Dictionary: by name1List of dictionaries: records2Match the structure to the question
Choose by how you will ask for the data: by position or order, use a list; by name, use a dictionary.

A dictionary makes a good counter:

words = ["a", "b", "a"]
counts = {}
for w in words:
    if w in counts:
        counts[w] = counts[w] + 1
    else:
        counts[w] = 1
print(counts)
{'a': 2, 'b': 1}

Real data has several facts per item, so each record is a dictionary and the records sit in a list:

students = [
    {"name": "Ann", "score": 70},
    {"name": "Bo", "score": 85},
]
print(students[1]["name"])
total = 0
for st in students:
    total = total + st["score"]
print(total)
Bo
155

Read students[1]["name"] from left to right: the item at position 1 (a dictionary), then its key "name". Data kept in tables and files is read this way. If a key is written in two slightly different ways, such as a gene symbol that has been changed into a date, the lookup fails or finds the wrong entry.

Step 5 Worked example (4 marks)

For data = [{"item": "pen", "qty": 3}, {"item": "ink", "qty": 2}] find data[0]["item"] and the total qty.

  1. data[0] is the first dictionary. (1 mark)
  2. Its "item" is pen. (1 mark)
  3. Total qty: 3 + 2 = 5. (1 mark)
  4. Answer: pen and 5. (1 mark)

Go deeper: the professor's notes

Every collection has a size. Compare the count out with the count in.
In

Items loaded.

Out

Items reported.

Gap

Must be zero.

LoadfileCountinProcessloopCountout
Check counts

Check

Count inCount outAction
65,53665,536investigate if input larger

At work: Lost rows

A file has 80,000 lines.

  1. Count the lines.
  2. Count the processed items.

What a careful practitioner decides. Never report a count without comparing it with the source.

Phase 3: Practise

Step 6 Learner practice (instant-marked)

1. To look up a price by item name, use:

2. Counting how many times each word appears suits:

3. students[0]["name"] reads:

4. A list of dictionaries is good for:

Phase 4: Close

Step 7 Recap

  • List by position; dictionary by key.
  • A dictionary counts with if key in dict.
  • Records are dictionaries inside a list.

Step 8 Exit ticket (ungraded)

Count the letters in ["x", "y", "x", "x"] with a dictionary.

Private: nothing you type here is sent or stored.

Step 9 Go further (Extension)

Make a list of three students as dictionaries and print the highest score.

In industry: 65,536 rows

A health agency's reports in October 2020 omitted 15,841 positive cases because lab files were loaded into a format limited to 65,536 rows.

Link to this lesson. Every collection has a size. A good program checks that the count of items out equals the count of items in.

Source: GOV.UK, PHE statement on delayed reporting (4 October 2020); IT News (2020)

Common mistakes

MistakeWhy it fails
Using a list when you need lookupYou will search every time.
Forgetting to add a new key before adding to itCheck with in, or set it to 1 first.
Mixing the order of [position][key]Position first, then key.

Limits. Real files often have missing or inconsistent keys; Module 6 shows how to handle them.

Flashcards for this lesson (3)

Tap a card to reveal the answer. Read the question, answer it aloud or in writing first, then check yourself against the explanation.

Card 1 of 3 · What is a KeyError and how do you avoid it?
MissingkeyCheckin or getDefaultvalue
KeyError

It means the key is not present. Test with in, or use get with a default so a missing key gives a value you choose.

Card 2 of 3 · How do you count items with a dictionary?
Empty{}If inadd 1Elseset 1
Counter

Loop over the items. If the key is already in the dictionary, add 1; otherwise set it to 1. This is a tally sheet for survey answers.

Card 3 of 3 · What is a list of dictionaries?
ListrecordsPosition[1]Key["name"]
Records

A list where each item is a dictionary holding one record, such as name and score. Read records[1]["name"] as position first, then key. Table data in files looks like this.

Review with flashcards

Test yourself on this module with workplace flashcards and detailed answers.

Open the module flashcards