Group records by an explicit key

Type one expression at a time and check its delimiters. · 163 words

Treat each experiment run as a record with a model, dataset, and score. An explicit key is the field deliberately chosen for grouping; here it is the dataset. Import groupby from itertools. This tool groups neighboring records with the same key, but it does not sort them. Use records = [('m1', 'books', 0.81), ('m3', 'books', 0.88), ('m2', 'news', 0.76)]. The books records are adjacent, so the grouping can be checked by hand.

Assign the groups with grouped = groupby(records, key=lambda row: row[1]). Each result pairs a dataset label with an iterator over that group's records. The loop for dataset, rows in grouped: print(dataset, list(rows)) prints books [('m1', 0.81), ('m3', 0.88)] and news [('m2', 0.76)]. The lambda selects column 1 but leaves each record intact. If m2 were placed before m3, the books records would not be adjacent and would appear in two groups. For AI experiment summaries, sort by the grouping field first, or use a dictionary when input order does not matter.

Check your recall

For the shown records, which datasets are yielded, and which runs belong to the books group?

Check your answer

The groups are books followed by news. The books group contains m1 and m3 because those records are adjacent and have the same dataset key.

Sources and credits

Original KeyTouch lesson. Background reading · Python Software Foundation · The Python Tutorial.