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.
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.
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.
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.