M9) Counting missing record values

A list contains dictionary records. Apply these requirements to count_empty(records):

  • Count every None value across all records.
  • Do not count 0 or an empty string; both are recorded values.
  • Every key is present. Count missing values, not absent keys.
  • No variable named worksheet is defined.

The example in Listing 1 has three missing values. record.values() visits the values stored in one dictionary.

Listing 1: Two records with three values represented by None.
records = [
    {"A": None, "B": 6, "C": 7, "D": 8},
    {"A": 9, "B": 10, "C": None, "D": None},
]

Compare the four implementations in Listing 2.

Listing 2: Alternatives that count missing values across dictionary records.
(a) Alternative A.
def count_empty(records):
    count = 0
    for record in records:
        for value in worksheet.values():
            if value is None:
                count += 1
    return count
(b) Alternative B.
def count_empty(records):
    count = 0
    for record in records:
        for value in record.values():
            if value is not None:
                count += 1
    return count
(c) Alternative C.
def count_empty(records):
    count = 0
    for record in records:
        for value in record.values():
            if value is None:
                count += 1
    return count
(d) Alternative D.
def count_empty(records):
    count = 0
    for record in records:
        count = 0
        for value in record.values():
            if value is None:
                count += 1
    return count

Which implementation satisfies the stated requirements?

  • record.values() provides the dictionary’s stored values without its keys and leaves it unchanged. An empty dictionary has no values to visit.
  • list(values) collects visited values into a list. For record = {"X": 4, "Y": None}, list(record.values()) gives [4, None].