Pure Python data and functions
Python lets you express small, repeatable data transformations without an AI library. A list stores a sequence of items, a dictionary associates keys with values, and a function packages a computation that can be reused. Counting categories is a useful first step in inspecting examples before training or evaluating a model.
Count categories in a help-desk dataset
Imagine a fictional shop with three support tickets. Each ticket is a record: a dictionary containing a category. The category is a string (text); the count is an integer (whole number). A list contains all three records. We assume every record contains a category string. No real customer data is used. The function below returns a number without changing its input or reading files.
def count_category(records, category): total = 0 for record in records: if record["category"] == category: total += 1 return total
records = [ {"category": "delivery"}, {"category": "billing"}, {"category": "delivery"},]for category in ["delivery", "billing", "other"]: print(category, count_category(records, category))print(count_category([], "delivery"))Output, one line at a time: delivery 2, billing 1, other 0, and 0. def starts a function, the names inside parentheses are its parameters, and indentation marks its body. total = 0 initializes a counter. The for loop visits each dictionary; record["category"] retrieves the stored value; == compares two values. When they match, += 1 adds one. return sends the final count back to the caller, and print displays it. Empty lists cause zero loop iterations, so the result is zero. Printing is not the same as returning: the return value can be used by another function.
Count words with a dictionary
A word frequency table is a simple representation of text, useful for inspecting repeated words. In this example lower() makes letter case consistent and split() separates whitespace-delimited pieces. This is not a linguistic tokenizer: punctuation remains attached and words may be divided differently in real language processing. A dictionary lookup with get(word, 0) returns zero for a missing key without inserting it. Assigning the incremented value stores the new count.
def word_counts(text): counts = {} for word in text.lower().split(): counts[word] = counts.get(word, 0) + 1 return counts
counts = word_counts("Blue box blue bag")print(counts["blue"])print(counts.get("green", 0))print(word_counts(""))The word blue occurs twice, green is absent, and an empty string produces an empty dictionary. Try "blue, blue": the comma stays attached to the first piece, so the two keys differ. Frequency is not meaning; a repeated word does not establish the intent or truth of a message.
Extract numerical values
A list comprehension builds a new list by evaluating an expression for each item. The following extracts the minutes field without modifying the original records. It is equivalent to creating an empty list and appending each value in a loop.
records = [{"minutes": 4}, {"minutes": 8}, {"minutes": 6}]minutes = [record["minutes"] for record in records]print(minutes)The result is [4, 8, 6], ready for a numerical summary. If a record lacks the key, ordinary bracket lookup raises KeyError; do not silently convert missing values to zero. Real datasets need an explicit missing-data policy, introduced next chapter.
Common mistakes and practice
Keep the counter initialization outside the loop, and return after all items are visited. Initializing inside the loop loses earlier matches; returning inside it stops after the first item. Lists and dictionaries are mutable, so avoid editing the input when the goal is a summary. Practice: write a function that counts records whose category is not the supplied category. For the three tickets above and delivery, the result is one; for an empty list it is zero. Test the empty case and ensure the input still contains its original records. The next lesson turns small functions into reproducible experiments.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Pure Python data and functions — understanding check
Apply Python data and reproducibility concepts to small synthetic examples.
What does count_category(records, "billing") return for the three-ticket example?
Why does count_category return zero for an empty list?
What dictionary does word_counts("blue, blue") return under the lesson’s rules?
Where should return total appear so all matching records are counted?
What happens if record["minutes"] is used on a dictionary without that key?