CodeRigor

FREE LESSON

Collections, grouping & deterministic order

Dictionaries, sets, comprehensions and stable sorting for experiment records and reproducible rankings.

Lists preserve sequence order; dictionaries map hashable keys to values and preserve insertion order; sets express membership and deduplication. A dict comprehension can overwrite a previous value when a key repeats. Decide whether duplicates mean overwrite, reject, count, or group before coding.

Keep every observation when grouping, then define ranking ties explicitly.

Grouping retains repeated keys
The three input observations create two independent lists; the second a observation appends instead of replacing.
Grouping retains repeated keys
The three input observations create two independent lists; the second a observation appends instead of replacing.
Python
counts = {}
for label in ["b", "a", "b"]:
    counts[label] = counts.get(label, 0) + 1
print(counts)  # {'b': 2, 'a': 1}

setdefault(key, []) is convenient for a grouping list. The default must be fresh for each group: sharing one list puts every row into every group. Comprehensions transform and filter; nested comprehensions need particular care because their order is the same as nested for loops.

Python
rows = [("control", 2), ("treatment", 5), ("control", 3)]
grouped = {}
for condition, score in rows:
    grouped.setdefault(condition, []).append(score)
print(grouped["control"])

Sorting is stable, but stability alone does not specify a meaningful tie breaker. sorted(counts, key=lambda k: (-counts[k], k)) sorts by decreasing frequency and then increasing label. Do not depend on set iteration order for exported experiment results. Sorted output makes diffs and reruns useful.

Stable sorting preserves encounter order for equal keys. A second key makes the intended alphabetical tie deterministic.

Frequency first, alphabetical ties
a and b both occur twice, so a ranks before b. c has a smaller frequency.
Frequency first, alphabetical ties
a and b both occur twice, so a ranks before b. c has a smaller frequency.

In the build, grouping preserves record order within each group. Ranking uses explicit alphabetical ties. Walk through ['b', 'a', 'b', 'a', 'c'] and write the expected rank before implementing it. Test two keys so a shared-list bug cannot hide behind a single group.

Watch & read

Free lectures, talks and readings that cover this skill from another angle. All resources →

Watch dictionary lookup, update and iteration. Use those operations to group runs by key, then follow the lesson’s explicit sorting keys and tie-breaking policy.