M10) Copying dictionary records within a threshold

A table is stored as a list of dictionaries. The first dictionary contains the column labels; every later dictionary contains an experiment ID and a numeric KPI (a measured performance value). copy_below_threshold(t, table) must return a new table containing a copied header followed by a copy of every data record whose KPI is less than or equal to t. It must preserve input order, record structure, and the input table.

The example in Listing 1 has threshold 0.7. Its required output contains the header and experiment IDs 1, 3, and 5. record.copy() creates a new dictionary with the same keys and values.

Listing 1: Header and five data records stored with named fields.
table = [
    {"id": "Experiment ID", "kpi": "KPI"},
    {"id": 1, "kpi": 0.5},
    {"id": 2, "kpi": 0.9},
    {"id": 3, "kpi": 0.7},
    {"id": 4, "kpi": 0.8},
    {"id": 5, "kpi": 0.1},
]

Compare the four implementations in Listing 2.

Listing 2: Alternatives for copying the header and qualifying dictionary records.
(a) Alternative A.
def copy_below_threshold(t, table):
    result = []
    for record in table:
        if record["kpi"] <= t:
            result.append(record.copy())
    return result
(b) Alternative B.
def copy_below_threshold(t, table):
    result = []
    for record in table[1:]:
        if record["kpi"] <= t:
            result.append(record.copy())
    return result
(c) Alternative C.
def copy_below_threshold(t, table):
    result = [table[0].copy()]
    for record in table[1:]:
        if record["kpi"] <= t:
            result.append(record.copy())
    return result
(d) Alternative D.
def copy_below_threshold(t, table):
    result = [table[0].copy()]
    for record in table[1:]:
        if record["kpi"] <= t:
            for key, value in record.items():
                result.append({key: value})
    return result

Which implementation satisfies the stated requirements?

  • record.copy() returns a new dictionary with the same keys and values. For record = {"id": 8, "kpi": 0.4}, its copy is {"id": 8, "kpi": 0.4}. The records here contain only numbers or strings.
  • record.items() visits (key, value) pairs: a record {"id": 8} yields the pair ("id", 8).
  • result.append(item) adds one item to the end of the list and returns None.
  • A slice table[1:] selects every item from position 1 onward without changing table.