Back to section lessons
16 min · easy · Lesson 2 of 8

Records, functions and clear errors

Work with dictionaries and lists, validate a dataset record, and count incident categories.

Lesson contents
  1. 1 A dataset record
  2. 2 Lists and dictionaries
  3. 3 Validating input
  4. 4 Return a validated copy
  5. 5 Task
  6. 6 Common mistake

A dataset record

Each course incident is represented by a dictionary. A key names a field, and its value stores the actual data:

Hover over a line or click it

record = {
    "id": "inc-001-a",
    "source_id": "inc-001",
    "text": "После релиза выросло время ответа",
    "label": "performance",
}
Line explanations
  1. Line 1. Creates a dictionary and stores it as record. A dictionary maps field names to values; the opening brace starts this collection of pairs.
  2. Line 2. Sets id to the identifier of this wording: inc-001-a. The colon separates a key from its value, quotes mark text, and the comma separates the next pair.
  3. Line 3. Stores the original case identifier in source_id. Different wordings of one case share a source_id. Later, this keeps them in one data split.
  4. Line 4. text stores the incident description the model will read. This is the input it uses to choose a category.
  5. Line 5. label contains the known correct category: performance, meaning a performance problem. During training, the model compares its answer with this value.
  6. Line 6. Closes the record dictionary. You can now read fields by key: for example, record["label"] returns "performance".

id is unique to each wording. source_id connects variants of the same original case so that they can later stay in the same data split. label contains one of the four allowed categories.

Lists and dictionaries

A list keeps records in order. Use a for loop to go through it:

Hover over a line or click it

records = [record]

for item in records:
    print(item["label"])
Line explanations
  1. Line 1. Creates records, a list with one item: the record dictionary from the previous example. These square brackets collect items into a list, preserving their order.
  2. Line 3. for iterates through records. Each item is available as item during its iteration; this example has just one iteration. The colon starts the indented loop body below.
  3. Line 4. Reads label from the current item dictionary and prints it with print(). For the list on the previous line, the result is performance. The indentation places this action inside the loop.

Keep counts in a separate dictionary. The get method returns zero if a category hasn't appeared yet:

Hover over a line or click it

counts: dict[str, int] = {}

for item in records:
    label = item["label"]
    counts[label] = counts.get(label, 0) + 1
Line explanations
  1. Line 1. Creates an empty counts dictionary for counters. dict[str, int] describes string keys and integer values, such as the category performance and the number 2. Python does not enforce this annotation on assignment.
  2. Line 3. Visits the records list one record at a time. The current record is called item; indented lines run for every record.
  3. Line 4. Reads label from the current record and saves it in the label variable. For the record above, its value is "performance".
  4. Line 5. Reads the previous count for this category and adds one. If counts has no entry for it, get(label, 0) returns the fallback zero. The result is written back: the first performance record gives 1, the second gives 2.

Validating input

The model should never receive a record with missing text or an unknown category. Validate before training, close to where you read the data.

Use TypeError for an incorrect type and ValueError for an invalid value:

Hover over a line or click it

def require_text(value: object) -> str:
    if not isinstance(value, str):
        raise TypeError("text must be a string")
    if not value.strip():
        raise ValueError("text must not be empty")
    return value
Line explanations
  1. Line 1. Declares require_text with a value argument. object allows any input, while -> str describes a string result after validation. The following lines perform the actual checks; these annotations do not.
  2. Line 2. isinstance(value, str) checks whether value is a string. not reverses the answer, so the if body runs for a non-string value such as 42.
  3. Line 3. raise stops the function with TypeError. This exception reports an incorrect input type; the message says text must be a string. For example, require_text(42) stops here.
  4. Line 4. strip() creates a string without whitespace at its edges. An empty string is false in a condition, so not makes this check true for empty or whitespace-only text. This is safe because the type was checked above.
  5. Line 5. Stops the function with ValueError: the type is correct, but the value is invalid. The message says text must not be empty. For example, require_text(" ") stops here.
  6. Line 6. Returns the original string when both checks pass. Whitespace is not removed from the result: require_text(" ok ") returns " ok ". strip() above was used only for validation.

An error message should name the field and the reason. bad input gives you little help: it doesn't say which value to fix.

Return a validated copy

Changing the input dictionary inside a function creates a hidden side effect. It's safer to build and return a new dictionary:

Hover over a line or click it

clean = {
    "id": record["id"].strip(),
    "source_id": record["source_id"].strip(),
    "text": record["text"].strip(),
    "label": record["label"],
}
Line explanations
  1. Line 1. Starts a new dictionary called clean. Fields are read from record, but the original dictionary is not modified. The cleaned values are stored separately.
  2. Line 2. Reads id from the original dictionary and removes whitespace at its edges. For example, " inc-001-a " becomes "inc-001-a" in the new dictionary; the original field stays unchanged.
  3. Line 3. Copies the original case identifier into clean, removing surrounding whitespace with strip(). This assumes the field exists and its string type has already been checked.
  4. Line 4. Copies the incident description without surrounding whitespace. strip() preserves spaces between words.
  5. Line 5. Copies the category unchanged. No strip() is used here, so the value must already have been validated: for example, the exact string "performance" is in the allowed categories.
  6. Line 6. Completes the new clean dictionary. This line does not return anything from a function. To return it to calling code, add a separate return clean statement inside the function.

The calling code keeps the original record, while the function's result contains normalized strings.

Task

Implement two functions in exercises/lesson02.py:

Hover over a line or click it

def validate_record(record) -> dict:
    ...

def count_categories(records) -> dict:
    ...
Line explanations
  1. Line 1. Declares the function that validates one record. -> dict describes the expected dictionary result. The task requires checking the fields and returning a new dictionary, leaving the original unchanged.
  2. Line 2. This is where validate_record goes. Three dots do not validate data or return a dictionary. Replace them with checks for types, required fields and the allowed category, then return the result.
  3. Line 4. Declares a function that counts categories in records. Its result must be a dictionary mapping each category name to its number of occurrences.
  4. Line 5. This is where count_categories goes. Iterate through the records, validate each with validate_record and increment its category count. An empty collection should return an empty dictionary {}.

validate_record must:

The set of keys must be exactly id, source_id, text, label. Missing or extra fields raise ValueError. An incorrect record or field value type raises TypeError.

count_categories validates each record with validate_record and returns the record count for each category. An empty list should produce an empty dictionary.

Hints

A set is a convenient place to keep allowed values. The check label not in ALLOWED_LABELS is easy to read and doesn't depend on order.

Don't catch your own TypeError and ValueError. The tests need the original exception type and a clear message.

Check

Hover over a line or click it

python -m pytest -q tests/test_exercises.py --student exercises -k lesson02
Line explanations
  1. Line 1. Runs pytest against tests/test_exercises.py. -q shortens the report, --student exercises selects your implementations, and -k lesson02 keeps only the second lesson checks. If something fails, the report shows the check and the function's actual behavior.

The tests check empty input, incorrect types, unknown categories and correct counting.

Where to find the solution

The full implementation is in solutions/lesson02.py. First, check that your function leaves the input dictionary unchanged and rejects whitespace-only text.

Hover over a line or click it

python -m pytest -q tests/test_exercises.py --student solutions -k lesson02
Line explanations
  1. Line 1. Runs the second lesson checks against references in solutions. -q shortens the output, --student solutions selects reference implementations, and -k lesson02 filters checks by lesson. Test your own solution with the command that uses --student exercises.

Common mistake

if not record["text"] won't reject a string of spaces. Check the type first, then apply strip(), and only then check whether the value is empty.

Done reading?

Mark the lesson as read to move your track progress forward.

Practice

Fix a local lab. The agent checks your work and gives hints if you get stuck.

Full access to all labs

$134 $67.00 for one year −50%

One payment, no auto-renewal · Terms

Buy for $67.00