Filtering and Transforming
Add Derived Field
Enrich a list of records by computing a new field from existing ones — here,
total = price × qty. The replay shows each record r alongside the
computed total, one iteration at a time.
By hand
The Pythonic way
A list comprehension with the dict-spread idiom {**r, 'total': r['p'] * r['q']}
produces each enriched record in one expression, without an explicit loop or
accumulator.
naive.py
records = [{'n': 'a', 'p': 2, 'q': 5}, {'n': 'b', 'p': 5, 'q': 6}, {'n': 'c', 'p': 3, 'q': 7}, {'n': 'd', 'p': 8, 'q': 3}, {'n': 'e', 'p': 4, 'q': 8}, {'n': 'f', 'p': 6, 'q': 9}]
# trace: ignore records, enriched
enriched = []
for r in records:
total = r['p'] * r['q']
new = {**r, 'total': total}
enriched.append(new)
print('RESULT:', [d['total'] for d in enriched])
library.py
records = [{'n': 'a', 'p': 2, 'q': 5}, {'n': 'b', 'p': 5, 'q': 6}, {'n': 'c', 'p': 3, 'q': 7}, {'n': 'd', 'p': 8, 'q': 3}, {'n': 'e', 'p': 4, 'q': 8}, {'n': 'f', 'p': 6, 'q': 9}]
enriched = [{**r, 'total': r['p'] * r['q']} for r in records]
print('RESULT:', [d['total'] for d in enriched])
RESULT: [10, 30, 21, 24, 32, 54]
Implementation notes
recordsandenrichedare excluded from tracing (# trace: ignore) because even two full-dict records push the list repr past 80 characters. The per-step visible state isr(the input record, ~25 chars),total(the computed value), andnew(the enriched record with the added field, ~40 chars) — exactly the three variables that teach "add a derived field".{**r, 'total': total}is the standard idiom for non-destructive dict enrichment: it copies every key fromrinto a new dict and adds'total'.- The
enriched.append(new)events are zero-delta in the trace becauseenrichedis ignored; the RESULT line confirms the accumulated output.