The Inbox as a Dataset

Before the LibrariesMedium+20 XP+20

The Inbox as a Dataset

You're getting emails ready for a program that will learn to spot spam. Each email has already been boiled down to a dictionary of counts, plus a verdict from a person — 1 for spam, 0 for not spam:

The training code expects a dataset object it can treat like a list. It only ever asks two things: how many examples are there? (len(data)) and give me example number i (data[i]). It also loops over the dataset with for.

Task: write a class EmailDataset, created as EmailDataset(records, features, label):

  • records is a list of dictionaries like the one above.
  • features is a list of key names — the measurements the program is shown.
  • label is one key name — the answer it should learn to give.

Example i is a tuple (feature_values, label_value):

  • feature_values is a list of the record's values for the names in features, in the order features lists them — not the order the dictionary happens to hold them in.
  • label_value is the record's value for label.

Some emails haven't been checked by a person yet, so their label is None. Those can't be learned from, so the dataset leaves them out completely: they don't count towards the length, and example 0 is the first record that does have a label. A label of 0 is a real verdict — not spam — and is kept.

len(data), data[i] (negative i too, as with a list), and looping with for or list(data) must all work. Asking for an example past the end should fail the way a list does.

Example

Examples

len(EmailDataset([{"links": 4, "caps": 12, "spam": 1}, {"links": 2, "caps": 30, "spam": None}, {"links": 0, "caps": 1, "spam": 0}], ["caps", "links"], "spam"))
returns 2
EmailDataset([{"links": 4, "caps": 12, "spam": 1}, {"links": 2, "caps": 30, "spam": None}, {"links": 0, "caps": 1, "spam": 0}], ["caps", "links"], "spam")[1]
returns ([1, 0], 0)

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run