Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Worked example · 20 min · revision 2

Choosing Lists, Dicts, Sets, Tuples and Dataclasses

Build the core of the word-frequency tool step by step and see why each step uses a list, a set, a dict, tuples or a dataclass.

Contentsand lesson path

What you will learn

  • Write functions that use core data structures (lists, dicts, sets, tuples) and handle errors with exceptions.

01. The problem

You have a dump of support tickets and want the most frequent words, to see what customers complain about before you build anything smarter. The output should be the top N words with their counts, most frequent first. The order must also be deterministic: the same input always gives the same output, so that you can test it.

Each step of the job has a natural data structure. Choosing well makes the code shorter and faster, and it documents your intent: a reader who sees a set knows that duplicates do not matter, while a list says that order and repeats do. This is the input used throughout the walk-through.

Python · the input
TICKETS = (
    "Refund not received. I asked for a refund on Monday!\n"
    "The app crashed when I opened the invoice.\n"
    "Invoice shows the wrong amount, please refund."
)

02. Step 1: split the text into a list of words

Start by turning text into words. Order and repetition both matter here, because you cannot count a word you have already thrown away as a duplicate, so the result is a list. A list comprehension builds it in one readable line: [expression for item in iterable if condition] means the expression, for each item, keeping only the items where the condition holds.

Python · tokenize()
import string


def tokenize(text: str) -> list[str]:
    """Lower-case the text, split on whitespace, strip punctuation at each end."""
    words = [raw.strip(string.punctuation) for raw in text.lower().split()]
    return [word for word in words if word]


tokens = tokenize(TICKETS)
print(len(tokens), tokens[:6])
Expected output
25 ['refund', 'not', 'received', 'i', 'asked', 'for']

The two comprehensions do two jobs: the first cleans every word, and the second drops anything that was pure punctuation and is now an empty string. Splitting on whitespace and stripping punctuation is a deliberate simplification. It keeps don't and e-mail as single words, and string.punctuation only covers ASCII symbols, so curly quotes survive. Tokenisers for language models split text into sub-word pieces instead; for counting words in tickets, this simple version is enough and easy to test.

03. Step 2: drop filler words with a set

Words such as the and of dominate any English text and tell you nothing. Keep them in a set, because the only question you ever ask is is this word in the collection?, and a set answers it by hashing the word instead of comparing it with every element. Use a frozenset for a constant: it cannot change after creation, so no other code can add to it by accident.

Python · stop words
STOP_WORDS = frozenset(
    {"a", "an", "and", "for", "i", "in", "is", "it", "of", "on", "the", "to"}
)
content = [word for word in tokens if word not in STOP_WORDS]
print(len(content), content[:5])
Expected output
17 ['refund', 'not', 'received', 'asked', 'refund']

Sets have one requirement that you will meet again with dict keys: their members must be hashable, which for built-in types means immutable. Strings, numbers and tuples of those qualify. Lists, dicts and sets do not, and Python stops with TypeError: unhashable type: 'list' if you try. Sets also make no promise about order, so never rely on the order you see when you loop over one.

04. Step 3: count with a dict, then with Counter

Counting is a lookup problem: for each word, find its current count and add one. A dict maps keys to values and finds a key in roughly constant time, however large it grows. Written by hand, the loop uses dict.get() with a default, so the first sighting of a word starts from zero instead of raising KeyError.

Python · counting by hand
counts: dict[str, int] = {}
for word in content:
    counts[word] = counts.get(word, 0) + 1
print(counts["refund"], counts["invoice"], counts.get("delivery", 0))
Expected output
3 2 0

The pattern is common enough that the standard library ships it. collections.Counter is a dict subclass that counts an iterable for you and adds helpers such as most_common(). Prefer it in real code, and know the loop above so that you can read code that does not use it.

Python · the same count with Counter
from collections import Counter

counter = Counter(content)
print(counter == counts, counter.most_common(3))
Expected output
True [('refund', 3), ('invoice', 2), ('not', 1)]

Look at the third entry. Twelve words share a count of 1, and most_common() lists tied words in the order it first met them, so which one comes third depends on the order of the input text. That is fine for exploring data, but it breaks the deterministic-output requirement, so the next step sorts explicitly.

05. Step 4: rank with tuples and a sort key

counts.items() yields (word, count) pairs as tuples: small, fixed-size, immutable groups in which each position has a meaning. sorted() accepts a key function that turns each item into the value to sort by. If that function returns a tuple, Python compares the tuples element by element, which gives you a multi-level sort for free. Here the negated count puts larger counts first, and the word breaks ties alphabetically.

Python · two-level sort
ranked = sorted(counts.items(), key=lambda item: (-item[1], item[0]))
print(ranked[:4])
Expected output
[('refund', 3), ('invoice', 2), ('amount', 1), ('app', 1)]

A lambda is a small unnamed function, convenient for one-line keys like this. Tuples have a second everyday use: because they are hashable, they can be dict keys or set members whenever one string is not enough to identify something, for example a (customer_id, ticket_id) pair.

06. Step 5: return records as dataclasses

The ranked tuples work, but item[1] makes every reader stop and remember what position 1 holds. For results that leave a function, use a dataclass. You list the fields with type hints, and the @dataclass decorator writes __init__, a readable printed form and == for you. frozen=True makes instances read-only, which suits results that you pass around and compare in tests, and slots=True makes each instance smaller in memory.

Python · WordCount records
from dataclasses import dataclass


@dataclass(frozen=True, slots=True)
class WordCount:
    word: str
    count: int


top = [WordCount(word, count) for word, count in ranked[:3]]
for record in top:
    print(record)
print(top[0] == WordCount("refund", 3))
Expected output
WordCount(word='refund', count=3)
WordCount(word='invoice', count=2)
WordCount(word='amount', count=1)
True

Compare this with TokenBudget from the previous lesson. That class protects a rule, so its methods are written by hand. WordCount is plain data, so the decorator does the boilerplate. A dict such as {"word": "refund", "count": 3} could hold the same data, but assigning to a misspelt key silently creates a new key, whereas a misspelt attribute name is an error that your editor and a type checker can catch.

07. Choosing at a glance

Pulling the walk-through together:

  • list: an ordered sequence in which repeats matter; you loop over it or index it by position.
  • tuple: a small, fixed group of values that belong together, a record you only read, or a key built from several values.
  • set or frozenset: unique items, when you ask is it in there? or combine collections with union and intersection.
  • dict: look values up, count them or group them by a key. Counter is a dict specialised for counting.
  • dataclass: a named record with typed fields that crosses function boundaries.

08. Check your understanding

Practice check · 3 questions

Pick the structure

Apply the choices from the walk-through to new cases.

Q1. You want to count bigrams, pairs of neighbouring words such as refund followed by please, in a dict. What should each key be?
Q2. What does sorted({"b": 2, "a": 2, "c": 5}.items(), key=lambda kv: (-kv[1], kv[0])) return?
Q3. record is a WordCount from Step 5, so it is frozen. What happens when you run record.count += 1?
Practice only: not graded, not saved, not evidence.

09. Apply it

Upgrade the wordfreq.py script you started in the previous lesson:

  1. Replace your counting code with tokenize(), the STOP_WORDS frozenset and a function count_words(words: list[str]) -> Counter[str] that drops stop words and counts the rest with collections.Counter.
  2. Add the WordCount dataclass and a function top_words(counts: Counter[str], n: int) -> list[WordCount] that ranks with the two-level sort key.
  3. Print the top five records for a sample text. Then reorder the sentences in your sample and confirm that the output does not change.

Stretch: add a bigrams(words: list[str]) -> Counter[tuple[str, str]] function. zip(words, words[1:]) pairs each word with the one after it.

10. Review prompt

Without looking back:

  1. For each of list, tuple, set, dict and dataclass, name one job in the word-frequency tool that it fits, and say why.
  2. Why can a tuple be a dict key when a list cannot?
  3. Why does the walk-through sort explicitly instead of trusting most_common()?
  4. From memory, write a sorted() call that orders (name, score) pairs by score, highest first, then by name.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check